<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>新浪微博</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<script src="js/oauth.js?v=1020"></script>
<script src="js/consumer.js?v=2.5"></script>
<script src="js/common.js?v=1.2"></script>
<script src="js/jquery-1.4.2.min.js"></script>
<script src="js/sha1.js"></script>
<link type="text/css" rel="stylesheet" id="fontstyle" href="css/yh.css" /> 
<style>
body {color:#333;line-height:180%;margin:0;padding:0;text-align:center;overflow:hidden;font-size:12px;}
*:focus {outline: 0;} 
ul,li{list-style:none;padding:0px;margin:0px;text-align:left;}
dl,dd{list-style:none;padding:0px;margin:0px;text-align:left;}
#header{background:url(images/header.png?v=1.3); width:400px;height:100px;position:relative}
#navbar{background:#fff;width:400px;height:23px;position:relative;margin-top:4px}
#profile_image{width:50px;height:50px;position:absolute;left:10px;top:6px;border:solid #fff 1px;-webkit-box-shadow:1px 2px 2px #bbb;}
#screen_name{position:absolute;left:70px;top:10px;height:30px;}
#screen_name a, #screen_name a:visited {font-size:14px;font-weight:bold;height:30px;color:#555;text-decoration:none}
#screen_name a:hover {color:#ff9900}
#search{position:absolute;left:11px;top:64px;width:161px;height:24px;text-align:left;background:url(images/weibo_search_bg.png);}
#search input{border:0px;width:140px;height:21px;color:#999999;padding-left:4px;background:none;}
#btn_search{position:absolute;left:140px;top:0px;width:21px;height:24px;display:block;cursor:pointer}
#mystats{position:absolute;left:70px;top:38px;color:#555}
#mystats a{color:#3b90d1;text-decoration:none;cursor:pointer}

#go_back{position:absolute;top:0px;right:50px;}
#historylist{position:absolute;top:0px;right:60px;font-size:12px;text-decoration:underline;border:solid #eee 1px;-webkit-border-radius:2px;width:55px;line-height:12px;padding:3px 0px 3px 0px;}
#mostview{position:absolute;top:7px;right:70px;font-size:12px;width:55px;line-height:12px;color:#000000;cursor:pointer;background:url(images/line.gif) no-repeat;height:14px;padding:3px 0px 0px 6px;;}
#new_weibo{position:absolute;left:10px;top:0px;background:url(images/header.png) -20px -104px;width:30px;height:20px;padding-left:15px;}
#new_comment{position:absolute;left:63px;top:0px;background:url(images/header.png) -136px -130px;width:30px;height:20px;padding-left:15px;}
#new_atme{position:absolute;left:116px;top:0px;background:url(images/header.png) -18px -155px;width:30px;height:20px;padding-left:10px;}
#new_msg{position:absolute;left:218px;top:0px;background:url(images/header.png) -137px -102px;width:30px;height:20px;padding-left:15px;}
#new_fans{position:absolute;left:163px;top:0px;background:url(images/header.png) -20px -129px;width:30px;height:20px;padding-left:15px;}
#navbar span{color:#000000;text-decoration:none;cursor:pointer}
#navbar span.on{color:#ff9900}
#navbar span b{position:absolute;display:none;top:-8px;left:-8px;background:#ff0000;display:;width:auto;height:14px;color:#fff;font-weight:normal;font-size:10px;-webkit-border-top-left-radius:7px;-webkit-border-top-right-radius:7px;-webkit-border-bottom-right-radius:7px;-webkit-border-bottom-left-radius:7px;line-height:12px;-webkit-box-shadow:2px 2px 2px #bbb;padding:0px 4px 0px 4px;z-index:777;-webkit-opacity:0.8;}
img{border:none}
#stage{width:400px;}
#namelist{position:absolute;right:75px;top:150px;z-index:8888;color:#fff;background:#999;padding:5px 0px 2px 0px;opacity:0.9;-webkit-border-radius:5px;cursor:pointer;display:none}
#namelist ul li{padding:0px 10px 0px 5px;position:relative;}
#namelist ul li b{font-weight:normal;padding-right:15px;font-size:10px;color:#ccc}
#namelist ul li:hover{background:#000000;color:#ccc}
#namelist ul li del{position:absolute;right:5px;top:4px;background:url(images/sicon.gif) -16px -6px;width:7px;height:8px;display:none;padding:2px;}

#panelbar{height:28px;background:url(images/weibo_content_topbar.gif?v=1.0)repeat-x;width:400px;position:relative;overflow:hidden;}
#panelbar .refresh{background:url(images/refresh.png) no-repeat 5px 4px;width:25px;height:22px;position:absolute;right:5px;top:3px;cursor:pointer}
#panelbar .dataloading{position:absolute;left:100px;top:6px;}
#panelbar .refresh:hover{background:url(images/refresh_hover.png) no-repeat 0px 0px;}
#panelbar .tablist{position:absolute;left:10px;top:6px;}
#panelbar .tablist span{float:left;display:block;color:#888;margin-right:10px;cursor:pointer}
#panelbar .tablist span.on{-webkit-border-top-left-radius:3px;-webkit-border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;-webkit-border-bottom-left-radius:3px;background:#A5A5A5;border:solid #808080 1px;color:#fff;height:14px;line-height:100%;padding:2px 3px 0px 3px;}

#userbar{position:absolute;height:63px;width:400px;top:-80px;z-index:500;background:#fafafa;border-bottom:solid #eee 1px;border-top:solid #eee 1px;}
#userbar .profile_image{width:50px;height:50px;position:absolute;left:0px;top:6px;border:solid #fff 1px;-webkit-box-shadow:1px 2px 2px #bbb;cursor:pointer}
#userbar .screen_name{position:absolute;left:60px;top:10px;height:30px;}
#userbar .user_tablist{position:absolute;left:60px;top:36px;}
#userbar .user_tablist a{float:left;display:block;color:#888;margin-right:10px;cursor:pointer;padding:4px 5px 2px 5px;height:14px;line-height:100%;-webkit-border-top-left-radius:3px;-webkit-border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;-webkit-border-bottom-left-radius:3px;background:#efefef;border:solid #ccc 1px;}
#userbar .user_tablist a.on{background:#A5A5A5;border:solid #808080 1px;color:#fff;}
#userbar .follow{margin-left:40px;height:17px;width:85px;text-align:right;color:#999}
#userbar .follow1{margin-left:20px;height:14px;width:auto;background:#89D900;color:#fff;border:solid #4EC000 1px;line-height:10%;padding:0px 5px 0px 5px;-webkit-border-radius:2px;cursor:pointer;}
#userbar .follow a{color:#92CBC4;text-decoration:none}
#userbar .follow1 img{margin-top:3px;}
#userbar .loading1{position:absolute;top:24px;left:192px}


#content{position:relative;clear:both;height:60px;width:400px;overflow-y:auto;overflow-x:hidden;text-align:left}
#footer{position:relative;clear:both;background:#F3F3F3;height:30px;width:400px;}
#feedback{position:absolute;right:97px;top:5px;cursor:pointer;color:#000000;width:40px;text-decoration:none;}
#setting{position:absolute;right:62px;top:5px;cursor:pointer;color:#000000;width:40px;}
#logout{position:absolute;right:5px;top:5px;cursor:pointer;color:#000000;width:60px;}
#writelong{position:absolute;right:65px;top:117px;width:40px;cursor:pointer;color:#555;background:;line-height:12px;padding-bottom:1px;border-bottom:solid #555 2px;text-align:center;}
#postpic{position:absolute;right:110px;top:117px;width:40px;cursor:pointer;color:#555;background:;line-height:12px;padding-bottom:1px;border-bottom:solid #555 2px;text-align:center;}
#writelong:hover,#postpic:hover{background:#B4E0FC;}
#share{position:absolute;left:228px;top:4px;width:72px;height:23px;background:url(images/weibo_btn_bglist.gif) no-repeat -81px 0px;cursor:pointer}
#share:hover{background:url(images/weibo_btn_bglist.gif) no-repeat -81px -46px}
.loading{color:#fff;width:30px;padding:2px;font-size:12px;position:absolute;top:10px;right:0px;display:none;z-index:999;line-height:12px;text-align:left}
.loadingbar{background:url(images/weibo_loadingbar_bg.gif) repeat-x;height:27px;width:400px;clear:both;color:#777777;text-align:center;padding-top:10px;position:relative}
.loadingbar img{position:absolute;left:150px;top:13px;}
#version{position:absolute;left:3px;top:5px;color:#999;width:60px;height:18px;}

#content ul li{line-height:150%;clear:both;height:auto;width:378px;margin-bottom:10px;}
#content ul li .profile_image{display:block;float:left;width:40px;height:40px;position:relative}
#content ul li .profile_image .notonline{width:9px;height:9px;border-radius:2px;border:solid #999 1px;background:#eee;position:absolute;left:25px;top:25px;}
#content ul li .profile_image .online{width:9px;height:9px;border-radius:2px;border:solid #4EC000 1px;background:#89D900;position:absolute;left:25px;top:25px;}
#content ul li .profile_image img{-webkit-border-radius:3px;cursor:pointer;border:solid #fff 1px;-webkit-box-shadow:1px 1px 1px #bbb;}
#content ul li .text{display:block;float:right;width:338px;color:#595959;word-break:break-all;position:relative}
#content ul li .text .screen_name screen_name{font-weight:bold}
#content ul li .text .creattime{position:absolute;right:0px;top:1px;color:#999}

#content ul li .text b{color:#F7810A;font-family: Constantia, Georgia;font-size:18px}
#content ul li .info{color:#999;width:338px;text-align:left;padding:5px 0px 10px 0px;position:relative}
#content ul li .info .comment_bar{position:absolute;right:0px;top:5px;width:190px;text-align:right;color:#3B90D1}
#content ul li .info a,#content ul li .info a:visited{color:#3B90D1;text-decoration:none;cursor:pointer;position:relative}
#content ul li .retweeted_topbar{background:url(images/weibo_content_bg1.gif?v=1) no-repeat;height:11px;width:342px;display:block;}
#content ul li .retweeted{color:#777;width:330px;text-align:left;border:solid #EEEEEE 1px;border-top:none;-webkit-border-bottom-right-radius:5px;-webkit-border-bottom-left-radius:5px;padding:5px;background:#f6f6f6}
#content ul li .retweeted .rinfo{width:320px;text-align:right;padding:5px 0px 0px 0px;position:relative;color:#999}
#content ul li .retweeted .rinfo span{position:absolute;left:0px;top:5px;}
#content ul li .retweeted .rinfo a{color:#7BB2DC;cursor:pointer;}
#content ul li .info .reply{position:absolute;right:4px;top:6px;color:#3B90D1;cursor:pointer}
#content ul li .info .reply:hover{text-decoration:underline}

#content ul li .info .delete1{position:absolute;right:4px;top:6px;cursor:pointer}
#content ul li .info .delete1 a:hover{text-decoration:underline}

.reply_box{display:none;width:332px;border:solid #ccc 1px;-webkit-border-radius:2px;padding:8px 3px 0px 3px;background:#FEFFE8;margin-bottom:6px;float:right;clear:both;}
.reply_box .input_comment{width:325px;}
.reply_box .input_comment .bar_postcomment{margin-bottom:0px;}
#content .line{height:0px;border-top:dotted #eee 1px;border-bottom:solid #fff 1px;}
user_weibo,user_fans, user_friends{color:#000000;cursor:pointer;}

/**微博评论列表**/
.comments_list_weibo{display:none;width:332px;border:solid #ccc 1px;-webkit-border-radius:3px;padding:8px 3px 8px 3px;background:#FEFFE8;margin-bottom:6px;}
#content ul li .text .comments_list_weibo ul li{line-height:150%;clear:both;height:auto;width:333px;margin-bottom:4px;color:#666}
.comments_list_weibo_r{display:none;width:322px;border:solid #ccc 1px;-webkit-border-radius:3px;padding:8px 3px 8px 3px;background:#FEFFE8;margin-bottom:6px;}
#content ul li .text .comments_list_weibo_r ul li{line-height:150%;clear:both;height:auto;width:322px;margin-bottom:4px;color:#666}

.comment_uname{color:#567DA0}
#content ul li .text .comments_list_weibo ul li.comment_info,#content ul li .text .comments_list_weibo_r ul li.comment_info{color:#aaa;margin-bottom:10px;position:relative}
.comment_info .reply{position:absolute;right:4px;top:1px;color:#000000;cursor:pointer}
.comment_info .reply:hover{text-decoration:underline}

.comment_list ul li .profile_image{display:block;float:left;width:35px;height:33px;cursor:pointer}
.comment_list ul li .profile_image img{-webkit-border-radius:3px;border:solid #fff 1px;-webkit-box-shadow:1px 1px 1px #bbb}
.input_comment{margin: 0px 0px 3px; padding: 2px; border-color: rgb(198, 198, 198); border-style: solid; border-width: 1px; font-size: 12px;word-wrap: break-word; line-height:18px;outline: medium none; resize:none;overflow:hidden;}
.comments_list_weibo .input_comment{width:325px;}
.comments_list_weibo_r .input_comment{width:315px;}
.btn_comment_post,.btn_repost_post{background:#4EC000;color:#fff;width:40px;height:15px;-webkit-border-radius:2px;line-height:100%;text-align:center;padding-top:1px;font-size:12px;cursor:pointer;display:block;float:right}

.bar_postcomment{text-align:right;padding-top:0px;clear:both;margin:6px 0px 8px 0px;height:20px;position:relative;}
.comments_list_weibo .bar_postcomment{width:328px;}
.comments_list_weibo_r .bar_postcomment{width:318px;}
.bar_postcomment .check{position:absolute;left:0px;top:0px;padding-left:18px;color:#aaa}
.bar_postcomment .check input{position:absolute;left:0px;top:-1px;}
.input_repost{margin: 0px 0px 3px; padding: 2px; border-color: rgb(198, 198, 198); border-style: solid; border-width: 1px; font-size: 12px;word-wrap: break-word; line-height:18px;outline: medium none; resize:none;overflow:hidden;}
.comments_list_weibo .input_repost{width:325px;}
.comments_list_weibo_r .input_repost{width:315px;}


#content screen_name{color:#000000;cursor:pointer;position:relative}
#content screen_name:hover{text-decoration:}

#content screen_name1{color:#000000;cursor:pointer;}
#content screen_name1:hover{text-decoration:underline}

#content tinylink{color:#000000;cursor:pointer;}
#content tinylink:hover{text-decoration:underline}

#writeweibo{background:#fefefe url(images/weibo_write.gif) no-repeat;width:45px;line-height:18px;position:absolute;right:5px;top:2px;cursor:pointer;padding:1px 0px 0px 15px;color:#3B90D1;z-index:999999999;border-radius:5px;}
#writeweibo:hover{color:#ff9900}

.weibopic{position:relative;}

.weibo_pic{-webkit-border-top-left-radius:1px;-webkit-border-top-right-radius:1px;-webkit-border-bottom-right-radius:1px;-webkit-border-bottom-left-radius:1px;cursor:pointer;border:solid #fff 1px;-webkit-box-shadow:1px 1px 1px #bbb;}
.weibopic_bar{display:none;position:absolute;left:-20px;top:-10px;-webkit-border-radius:3px;-webkit-opacity:0.2;background:#666;color:#fff;border:solid #fff 1px;padding:0px 5px 0px 5px;-webkit-box-shadow:1px 1px 1px #eee;cursor:pointer;text-decoration:none}
.weibopic_bar:hover{-webkit-opacity:1}
.more{clear:both;width:285px;text-align:right;border:solid #FFD800 1px;background:#FFFADD;margin-bottom:10px;padding-right:5px;;color:#999;cursor:pointer}
.more:hover{border:solid #FF9517 1px}

/**用户信息卡片**/
.profile_card{position:absolute;left:-300px;top:0px;width:300px;height:160px;background:url(images/layer_bg.png);display:none;-webkit-border-bottom-right-radius:5px;-webkit-border-bottom-left-radius:5px;-webkit-border-top-right-radius:5px;-webkit-border-top-left-radius:5px;z-index:1001;}
screen_name .profile_card .inner .screen_name:hover{text-decoration:none;}
.profile_card .inner{position:absolute;left:4px;top:4px;width:290px;height:150px;background:#fff;border:solid #bbb 1px;display:block;-webkit-border-bottom-right-radius:3px;-webkit-border-bottom-left-radius:3px;-webkit-border-top-right-radius:3px;-webkit-border-top-left-radius:3px;z-index:1002;overflow:hidden}
.profile_card .arrow_y{position:absolute;top:83px;left:-7px;background:url(images/layer_arrow.png) no-repeat 0px -24px;width:12px;height:21px;z-index:1003;display:block}
.profile_card .arrow_x{position:absolute;top:-7px;left:142px;background:url(images/layer_arrow.png) no-repeat 0px 0px;width:16px;height:12px;z-index:1003;display:block}
.profile_card .inner .card_profile_img{width:50px;height:50px;display:block;position:absolute;left:6px;top:10px;border:solid #fff 1px;-webkit-box-shadow:1px 1px 1px #bbb}
.profile_card .inner .screen_name{position:absolute;left:63px;top:7px;color:#0078C2;font-weight:normal;}
.profile_card .inner #online_status{width:100px;position:absolute;left:10px;top:4px;}
.profile_card .inner .notonline{width:9px;height:9px;border-radius:2px;border:solid #999 1px;background:#eee;float:left;display:block;margin:3px 3px 0px 0px;}
.profile_card .inner .online{width:9px;height:9px;border-radius:2px;border:solid #4EC000 1px;background:#89D900;float:left;display:block;margin:3px 3px 0px 0px;}
.profile_card .inner .screen_name b{color:#F7810A;font-family: Constantia, Georgia;font-size:18px;}
.profile_card .inner .location{position:absolute;left:63px;top:26px;color:#999;text-align:left;}
.profile_card .inner .info{position:absolute;left:63px;top:46px;color:#999;text-align:left;}
.profile_card .inner a{font-weight:normal;color:#0078B6;cursor:pointer}
.profile_card .inner .desc{position:absolute;left:5px;top:70px;color:#999;text-align:left;line-height:130%}
.profile_card .inner .opbar{position:absolute;left:0px;top:123px;color:#999;text-align:left;height:25px;width:290px;-webkit-border-bottom-right-radius:3px;-webkit-border-bottom-left-radius:3px}
.profile_card .inner .opbar .follow{position:absolute;right:10px;top:2px;height:17px;width:95px;text-align:right;}
.profile_card .inner .opbar .follow1{position:absolute;right:6px;top:3px;height:14px;width:auto;background:#89D900;color:#fff;border:solid #4EC000 1px;line-height:100%;padding:2px 2px 0px 1px;-webkit-border-top-right-radius:2px;-webkit-border-top-left-radius:2px;-webkit-border-bottom-right-radius:2px;-webkit-border-bottom-left-radius:2px;cursor:pointer;}
.profile_card .inner .opbar .follow a{color:#92CBC4;text-decoration:none}
.profile_card .inner .noresult{position:absolute;left:120px;top:70px;font-weight:bold}

/**微博输入框**/
#weibobox_container{width:382px;height:142px;position:absolute;display:none;left:-400px;z-index:1111111;overflow:hidden}
#weibobox{width:370px;height:130px;position:absolute;left:0px;top:100px;background:#f6f6f6;border:solid #e6e6e6 1px;border-top:solid #fff 1px;padding:5px;text-align:left;-webkit-border-bottom-right-radius:7px;-webkit-border-bottom-left-radius:0px;-webkit-opacity:0.95;color:#666;}
#weibobox textarea{position:absolute;left:5px;top:25px;width:362px;height:80px;font-size:12px;resize:none;border-radius:4px;border:solid #ccc 1px;background:#FFFCD9;word-break:break-all;}
#btn_weibo_post{background:#4EC000;color:#fff;width:50px;height:16px;border-radius:2px;position:absolute;right:8px;top:115px;line-height:100%;text-align:center;padding-top:3px;font-size:12px;cursor:pointer}
#weibobox .post_loading{position:absolute;right:180px;top:70px;display:none}
#weibobox .close{background:url(images/bg_list1.png) -232px -84px;width:15px;height:15px;position:absolute;right:4px;top:4px;cursor:pointer}
#weibobox .close:hover{background:url(images/bg_list1.png) -252px -84px;}
#weibobox .insertbar{position:absolute;top:115px;left:5px;}
#weibobox .insertbar span{width:52px;height:16px;color:#2B4A78;cursor:pointer;display:block;float:left}
#weibobox .insertbar span b{width:16px;height:16px;display:inline-block;margin-bottom:-3px;margin-right:2px;}
#weibobox .insertbar .emotions b{background:url(images/weibo_ico.png) 0px 0px}
#weibobox .insertbar .topic b{background:url(images/weibo_ico.png) 0px -135px;}
#weibobox .insertbar .friends b{background:url(images/bg_list1.png) -144px -33px;}

#word_count b{font-size:18px;font-family: Constantia, Georgia;}
#insertblock{-webkit-box-shadow: rgba(51, 51, 51, 0.199219) 2px 2px 2px;position:absolute;left:0px;top:275px;width:380px;height:40px;border:solid #D2D2D2 1px;z-index:88888;background:#fff;display:none;-webkit-opacity:0.90;}
#insertblock .topbar{background: -webkit-gradient(linear, 0 0, 0 100%, from(#FEFEFE), to(whiteSmoke));border-bottom: 1px solid #CFCFCF;height: 24px;width: 100%;position:relative;}
#insertblock .title{position:absolute;top:0px;height:23px;padding:2px 10px 0px 10px;background:#fff;border-right:solid #cfcfcf 1px;}
#insertblock .close{background:url(images/bg_list1.png) -232px -84px;width:15px;height:15px;position:absolute;right:4px;top:4px;cursor:pointer}
#insertblock .close:hover{background:url(images/bg_list1.png) -252px -84px;}
#insertblock .inner{height:205px;overflow:auto;padding:5px 0px 0px 5px;position:relative;}
#insertblock .inner ul li{float:left;padding:2px;border:dotted #DFE6F6 1px;width:24px;height:24px;text-align:center;cursor:pointer;margin:1px;}
#insertblock .inner dl dd{color:#777;cursor:pointer;float:left;height:16px;width:150px;display:block;padding:3px 2px 1px 2px;line-height:12px;}
#insertblock .inner dl dd:hover{background:#D2E9FA}

/**确认框**/
#confirmbox_container{position:absolute;top:300px;left:50px;z-index:1101;width:205px;height:95px;overflow:hidden}
#confirmbox{position:absolute;top:95px;left:0px;background:url(images/layer_bg.png);-webkit-border-bottom-right-radius:5px;-webkit-border-bottom-left-radius:5px;-webkit-border-top-right-radius:5px;-webkit-border-top-left-radius:5px;width:205px;height:96px}
#confirmbox .inner{position:absolute;left:4px;top:4px;border:solid #C6C6C6 1px;background:#fff;width:195px;height:85px;color:#666666}
#confirmbox .msg{position:absolute;background:url(images/btn_ok_cancel_repeat.png) no-repeat 0px -50px;top:15px;left:10px;width:150px;height:20px;text-align:left;padding-left:20px}
#confirmbox .confirm{position:absolute;background:url(images/btn_ok_cancel_repeat.png) no-repeat 0px 0px;top:45px;left:30px;width:57px;height:24px;cursor:pointer}
#confirmbox .cancel{position:absolute;background:url(images/btn_ok_cancel_repeat.png) no-repeat -67px 0px;top:45px;left:100px;width:57px;height:24px;cursor:pointer}
#confirmbox .confirm:hover{background:url(images/btn_ok_cancel_repeat.png) no-repeat 0px -25px;}
#confirmbox .cancel:hover{background:url(images/btn_ok_cancel_repeat.png) no-repeat -67px -25px;}

/**错误提示框**/
#errorbox_container{position:absolute;top:200px;left:80px;z-index:99999;width:240px;height:125px;overflow:hidden;opacity:0.8}
#errorbox{position:absolute;top:125px;left:0px;background:url(images/layer_bg.png);-webkit-border-bottom-right-radius:5px;-webkit-border-bottom-left-radius:5px;-webkit-border-top-right-radius:5px;-webkit-border-top-left-radius:5px;width:240px;height:125px}
#errorbox .inner{position:absolute;left:4px;top:4px;border:solid #C6C6C6 1px;background:#fff;width:230px;height:115px;color:#666666}
#errorbox .msg{position:absolute;top:30px;left:20px;background:url(images/sicon.gif) no-repeat -83px -108px;width:200px;height:20px;text-align:left;padding-left:20px;font-size:14px;}
#errorbox .redo{position:absolute;background:url(images/btn_ok_cancel_repeat.png?v=1) no-repeat -135px 0px;top:65px;left:50px;width:57px;height:24px;cursor:pointer}
#errorbox .cancel{position:absolute;background:url(images/btn_ok_cancel_repeat.png) no-repeat -67px 0px;top:65px;left:120px;width:57px;height:24px;cursor:pointer}
#errorbox .redo:hover{background:url(images/btn_ok_cancel_repeat.png?v=1) no-repeat -135px -25px;}
#errorbox .cancel:hover{background:url(images/btn_ok_cancel_repeat.png) no-repeat -67px -25px;}
.destroy{cursor:pointer}

/**@选择**/
#friendsselector{position:absolute;left:5px;top:180px;border:solid #ccc 1px;background:#fff;width:120px;padding:1px;z-index:100099}
#friendsselector span{display:block;width:116px;text-align:left;height:20px;float:left;color:#777;padding:2px}
#friendsselector dl dd{color:#555;cursor:pointer;float:left;height:16px;width:116px;display:block;padding:3px 2px 1px 2px;line-height:12px;}
#friendsselector dl dd:hover{background:#eee}

</style>
<script>
var port = "";

//屏幕高度
var screenHeight = screen.height;
//窗口拉伸后的高度
var newWindowHeight = screenHeight - 200;
newWindowHeight = (newWindowHeight > 590) ? 590 : newWindowHeight;
//数据容器高度
var newContentHeight = newWindowHeight - 183;

//是否有新微博更新
var newWeibo = 0;

var seWeiboid = 1708850973;

//新微薄条数
var newWeiboCount = 0;

var wordCountLimit = 140;

var authWindowWidth = 670;
var authWindowHeight = 480;

var readCount = 40;

var OAuth = OAuth || {};

var dataLoading = 0;
var dataType = "";
var accessToken = localStorage.getItem("oauth2_accessToken");
var showWizard = localStorage.getItem("show_wizard");
var startWizard = 0;
var accessor = consumer["sina"];
var uid = "";
var userInfo = {};
var facesList = {};

if(accessToken){
	initFacesList();
}


function doCreatePort(){
	port = chrome.extension.connect();
	console.log(port);
}

function doPostMessage(data){

	port.postMessage(data);

}

function getUidByAccessToken() {
    var message = {
        method: "get", action:accessor.serviceProvider.uidURL
		 , parameters: [["scope", "http://www.google.com/m8/feeds/"]]
    };
    var requestBody = OAuth.formEncode(message.parameters);
    var request = newXMLHttpRequest();
    request.onreadystatechange = function receiveRequestToken() {
        if (request.readyState == 4) {
			if (request.status == 200){
				var results = JSON.parse(request.responseText);
				uid = parseInt(results["uid"]);
				//向后台发送通知，更新acesstoken
				$("#main").fadeIn();
				jsonData = {cmd:"newaccess",value:accessToken};
				doPostMessage(jsonData);
				listenNavClick(uid);
				getUserInfo(uid);
				if(!checkIfLocal(showWizard)){
					initWizard();
				}
			} else {
				var results = JSON.parse(request.responseText);
				if(results["error"] != undefined ){
					if(results["error"] == "invalid_access_token"){
						gotoAuthPage();
					} else if(results["error_code"] == "21321"){
						return;
					}	
				}	
			}
        }
    };

    request.open(message.method, message.action, true); 
    request.setRequestHeader("Authorization", "OAuth2 " + accessToken);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.send(requestBody);
}

function getUserInfo(uid, type, type1) {
	if(type == "card"){
		var requestStr = "?screen_name=" + uid;
	}else if(type == "userbar"){
		var requestStr = "?screen_name=" + uid;
	} else {
		var requestStr = "?uid=" + uid
	}
    var message = {
        method: "get", action:accessor.serviceProvider.userInfoURL + requestStr
		 , parameters: [["scope", "http://www.google.com/m8/feeds/"]]
    };
    var requestBody = OAuth.formEncode(message.parameters);
    var request = newXMLHttpRequest();
    request.onreadystatechange = function receiveData() {
        if (request.readyState == 4) {
			if (request.status == 200){
				var results = request.responseText;
				var userInfo = JSON.parse(results);
				if(type == "card"){
					showCardInfo(userInfo);
				}else if(type == "userbar"){
					showUserBar(userInfo, type1)
					if(type1 == "userweibo"){
						getDataFromApi(type1, {"screen_name":userInfo["name"],"refresh":1,"noresult":0});
					} else {
						getDataFromApi(type1, {"uid":userInfo["id"],"refresh":1,"noresult":0});
					}
				} else {
					localStorage.setItem("oauth2_userinfo", results);		
					showUserInfo(userInfo);
				}
				
			}else {
				var errorRs = JSON.parse(request.responseText);
				if(errorRs["error_code"] == "20003"){
					if(type == "card"){
						showCardInfo(null);
					} else if(type == "userbar"){
						showErrorBlock("该用户不存在!");
					}		
				}
			}
        }
    };
	
    request.open(message.method, message.action, true); 
    request.setRequestHeader("Authorization", "OAuth2 " + accessToken);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.send(requestBody);
}

function getUnread() {
	showHideLoading(1);
    var message = {
        method: "get", action:accessor.serviceProvider.unreadURL
		 , parameters: [["scope", "http://www.google.com/m8/feeds/"]]
    };
    var requestBody = OAuth.formEncode(message.parameters);
    var request = newXMLHttpRequest();
    request.onreadystatechange = function receiveData() {
        if (request.readyState == 4) {
			if (request.status == 200){
				var results = JSON.parse(request.responseText);
				newWeiboCount = results["status"];
				showUnreadInfo(results);
				showHideLoading(0);
			
				//向后台发送通知，更新未读信息条数
				jsonData = {cmd:"openpop",value:1};
				doPostMessage(jsonData);
			}else {
				
				showHideLoading(0);
				//gotoAuthPage();
			}
        }
    };

    request.open(message.method, message.action, true); 
    request.setRequestHeader("Authorization", "OAuth2 " + accessToken);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.send(requestBody);
}

//未读信息清零
//type 	true 	int, 1~4 	需要清零的计数类别，值为下列四个之一：1. 评论数，2. @me数，3. 私信数，4. 关注数 
function resetUnread(type) {
    var message = {
        method: "get", action:accessor.serviceProvider.resetUnreadURL+"?type="+type
		 , parameters: [["scope", "http://www.google.com/m8/feeds/"]]
    };
    var requestBody = OAuth.formEncode(message.parameters);
    var request = newXMLHttpRequest();
    request.onreadystatechange = function receiveData() {
        if (request.readyState == 4) {
			if (request.status == 200){
				//向后台发送通知，更新未读信息条数
				jsonData = {cmd:"resetunread",value:1};
				doPostMessage(jsonData);
			}else {
				return;
			}
        }
    };

    request.open(message.method, message.action, true); 
    request.setRequestHeader("Authorization", "OAuth2 " + accessToken);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.send(requestBody);
}

function followUser(type, uid, following, follow_me, ele){
	var actionUrl = (type == "destroy") ? "https://api.weibo.com/2/friendships/destroy.json" : "https://api.weibo.com/2/friendships/create.json";
	var message = {
		method: "post",action:actionUrl
		, parameters: [["scope", "http://www.google.com/m8/feeds/"]]
	};
	var requestBody = OAuth.formEncode(message.parameters);
	var request = newXMLHttpRequest();
    request.onreadystatechange = function receiveData() {
        if (request.readyState == 4) {
			if (request.status == 200){
				if(ele){
					if(type == "destroy"){
						showFriendship(0, follow_me, uid, ele)
					} else {
						showFriendship(1, follow_me, uid, ele)
					}
				}
			}else {
				return;
			}
        }
    };

    request.open(message.method, message.action, true); 
    request.setRequestHeader("Authorization", "OAuth2 " + accessToken);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.send("uid="+uid);
}


//展示用户信息
function showUserInfo(userInfo){
	$("#profile_image").html("<img src='" + userInfo["profile_image_url"] + "' />");
	$("#screen_name").html("<a href='javascript:void(0);'>" + userInfo["name"] + "</a>");
	$("#mystats").html("关注<a id='myfriends'>" + userInfo["friends_count"] + "</a>  粉丝<a id='myfans'>" + formatCount(parseInt(userInfo["followers_count"]))+ "</a>  收藏<a id='myfavorites'>" + userInfo["favourites_count"] + "</a>  微博<a id='myweibo'>" + userInfo["statuses_count"] + "</a>");
	var uid = userInfo["id"];
	listenNavClick(uid);
	$("#myweibo").click(function(){
		loadingMyWeibo();
	});
	$("#myfavorites").click(function(){
		loadingFavorites();
	});
	$("#myfans").click(function(){
		loadingFans("fans", uid);
	});
	$("#myfriends").click(function(){
		loadingFans("friends", uid);
	});
	getUnread("sina");
}

function showUserBar(userInfo, type){
	var theUid = parseInt(userInfo["id"]);
	var following = userInfo["following"];
	var follow_me = userInfo["follow_me"];
	var name = userInfo["name"];
	var html = "<div class='profile_image'><img src='" + userInfo["profile_image_url"] + "' /></div><div class='screen_name'>" + userInfo["name"] + "<span class='friendship'></span></div><div class='user_tablist'><a class='friends'>关注 " + userInfo["friends_count"] + "</a>  <a class='fans'>粉丝 " + (parseInt(userInfo["followers_count"]))+ "</a>  <a class='weibo'>微博 " + userInfo["statuses_count"] + "</a</div>";
	$("#userbar").html(html);
	$("#panelbar").css("overflow", "visible");
	if(type == "fans"){
		$("#userbar .fans").addClass("on");
	}else if(type == "friends"){
		$("#userbar .friends").addClass("on");
	} else {
		$("#userbar .weibo").addClass("on");
	}
	showFriendship(following,follow_me,theUid, ".friendship");
	$("#userbar .user_tablist .friends").click(function(){
		$("#userbar .user_tablist .on").removeClass("on");
		$(this).addClass("on");
		$("#content").animate({scrollTop:0},200);
		dataType = "friends";
		showDataLoading();
		getDataFromApi("friends",{"refresh":1, "uid":theUid});
		var lastAction = {"method":"gotoUserWeibo","uid":"","name":name, "type":"friends"};
		saveAction(lastAction);
	});

	$("#userbar .user_tablist .fans").click(function(){
		$("#userbar .user_tablist .on").removeClass("on");
		$(this).addClass("on");
		$("#content").animate({scrollTop:0},200);
		dataType = "fans";
		showDataLoading();
		getDataFromApi("fans",{"refresh":1, "uid":theUid});
		var lastAction = {"method":"gotoUserWeibo","uid":"","name":name, "type":"fans"};
		saveAction(lastAction);
	});

	$("#userbar .user_tablist .weibo").click(function(){
		$("#userbar .user_tablist .on").removeClass("on");
		$(this).addClass("on");
		dataType = "weibo";
		$("#content").animate({scrollTop:0},200);
		showDataLoading();	
		getDataFromApi("userweibo", {"uid":theUid,"refresh":1,"noresult":0});
	});

	var avatarTime = "";
	$("#userbar .profile_image").mouseenter(function(){
		avatarTime = setTimeout(function(){showAvatarLarge()}, 1000);
	});

	var showAvatarLarge = function(){
		var html = "<div class='profile_image_big' style='position:absolute;left:58px;top:128px;width:0px;height:0px;z-index:9999;-webkit-border-radius:3px;cursor:pointer;border:solid #fff 1px;-webkit-box-shadow:3px 2px 2px #eee;'><img src='" + userInfo["avatar_large"] + "' /></div>";
		$("body").append(html);
		$(".profile_image_big").animate({height:180,width:180});	
	}

	$("#userbar .profile_image").mouseleave(function(){
		clearTimeout(avatarTime);
		setTimeout(function(){$(".profile_image_big").animate({height:0,width:0},300, "linear", function(){$(".profile_image_big").remove();});}, 500);
		
	});
}

function preDataLoading(ele){
	$("#panelbar").height(28);
	$("#panelbar").css("overflow", "hidden");
	$("#userbar").css("top","-80px");
	$("#content").height(newContentHeight);
	$("#navbar span.on").removeClass("on");
	ele.addClass("on");
	window.resizeTo(400,newWindowHeight);
	$("#content").animate({scrollTop:0},200);
	//$("#content").html("");
	$("#content li").fadeOut("slow");
	showDataLoading();
}

function listenDataRefresh(){
	$("#panelbar .refresh").click(function(){
		if(dataLoading == 0){
			$("#content").animate({scrollTop:0},200);
			showDataLoading();
			configData["refresh"] = 1;
			configData["readcache"] = 0;
			getDataFromApi(dataType, configData);
		}
	});
}

var pd = 0;
function showCloseWeiboPostBox(type){
	var ele = $("#weibo_content");
	if(type == "show"){
		$("#weibobox_container").show();
		$("#weibobox_container").css("left", "0px");
		$("#weibobox_container").css("top", "155px");
		$("#weibobox").animate({top:0}, 200, "linear", function(){			
			ele.focus();
			if(checkIfLocal(localStorage.getItem("weibo_content"))){
				var content = localStorage.getItem("weibo_content");
				$("#weibo_content").val(content);
			}
			countWord(ele, $("#word_count"));
			if(startWizard == 1){
				var partHtml = "<div style='position:absolute;right:6px;top:138px;width:140px;' id='follow_official'><input type='checkbox' style='position:absolute;left:0px;top:1px;' checked /><span style='position:absolute;left:20px;top:0px;'>关注官方微博</span></div>";
				$("#weibobox_container").height(160);
				$("#weibobox").animate({height:148}, 200, "linear", function(){
					$("#weibobox").append(partHtml);
				});
			}
		});
	} else {
		$("#insertblock").remove();
		$("#weibobox").animate({top:100},200, "linear", function(){$("#weibobox_container").hide();});
	}
}

var pd = 0;
function initWeiboTextpost(){
	var ele = $("#weibo_content");
	var obj = document.getElementById("weibo_content");
	var obj_receive = document.getElementById("input_receive");
	$("#writeweibo").click(function(){
		if($("#weibobox_container").css("display") != "none"){
			showCloseWeiboPostBox("close");
		} else {
			showCloseWeiboPostBox("show");
		}
		;
		if(startWizard == 1){
			$("#tip_pop").fadeOut();
		}
	});

	$("#btn_weibo_post").click(function(){
		var text = ele.val();
		var i = 1;
		var j = 0;
		if(text == ''){
			showMsgTip("微博内容不能为空！", $("#weibobox_container"), 120,40, "#ff0000");
			$("#weibo_content").focus();
		}else{
			var content = ele.val();
			var ctype = $("#contenttype").val();
			var url= $("#wurl").val();
			postWeibo(content, ctype, url);
			if($("#follow_official input").attr("checked") == true){
				followUser("create", seWeiboid);
			}
			if($("#wizard_overflow").css("display") != "none"){
				$("#wizard_overflow").fadeOut();
				$("#follow_official").remove();
				$("#weibobox").height("130px");
				$("#weibobox_container").height("142px");
				startWizard = 0;
			}
		}
	});


	$("#weibobox .close").click(function(){
		showCloseWeiboPostBox("close");
		if($("#weibobox").height() == 148){	
			$("#wizard_overflow").fadeOut();
			$("#follow_official").remove();
			$("#weibobox").height("130px");
			$("#weibobox_container").height("142px");
			$("#weibo_content").val("");
			startWizard = 0;
		}
	});
	$("#msgbox .close").click(function(){
		showCloseMsgSendBox("close");
	});
	$("#weibo_content").keyup(function(){
		countWord(ele, $("#word_count"));
		saveWord2Storage("weibo_content", $(this).val());
	});
	
	$(".topic").click(function(){
		var insertText = "#话题#";
		var text = ele.val();		
		var n = parseInt(text.indexOf(insertText));
		if(n >= 0){
			ele.val(text);
			selectText(obj, n+1, n+13);
		} else {
			text += insertText;
			var n = text.indexOf(insertText);
			ele.val(text);
			selectText(obj, n+1, n+13);
		}
		countWord($("#weibo_content"), $("#word_count"));
	});
	$(".emotions").mouseover(function(){
		$(this).children("b").addClass("hover");
	});
	$(".emotions").mouseleave(function(){
		$(this).children("b").removeClass("hover");
	});
	$(".emotions").click(function(){
		initInsertBlock("常用表情", "emotion", obj);
	});
	
	$(".friends").click(function(){
		initInsertBlock("@朋友", "friends", obj);
	});

	$("#input_receive").click(function(){
		if($("#receive_selector").html() == null){
			getFriendsSelector(obj_receive, "receive");
		}
	});	

	$(document).click(function(){
		if($(this).attr("id") != "friendsselector"){
			$("#friendsselector").remove();
		}
	});
}

function initInsertBlock(title, type, cobj){
	var innerHtml = "";
	if(!$("#insertblock").html()){
		var html = "<div id='insertblock'><div class='topbar'><span class='title'></span><span class='close'></span></div><div class='inner'></div></div>";
		html = html.replace("%innerHtml%", innerHtml);
		$("body").append(html);
		$("#insertblock").fadeIn();
	}
	$("#insertblock .title").text(title);
	if(type == "emotion"){
		$("#insertblock .title").css("border-left","none");
		$("#insertblock .title").animate({left:"0px"});
		$("#insertblock").animate({height:"240px", width:"380px", left:"0px"},300,"linear", function(){
			$("#insertblock .inner").html(getEmotionSelector());
			$(".inner ul li").click(function(){
				var emotionTitle = $(this).children("img").attr("title");
				insertText2Textarea(cobj, emotionTitle);
				countWord($("#weibo_content"), $("#word_count"));
			});
		});
	} else if(type == "friends"){
		$("#insertblock .inner").html("");
		$("#insertblock .title").animate({left:"0px"});
		$("#insertblock .title").css("border-left","none");
		$("#insertblock").animate({height:"240px", width:"180px", left:"100px"}, 300, "linear", function(){
			showFriendsSelector(cobj);
		});	
	}
	$("#insertblock .close").click(function(){
		$("#insertblock").remove();
	});
}

function showFriendsSelector(cobj){
	var html = "<div id='keyword_div' style='text-align:left;float:left;'><input type='text' id='at_keyword' style='width:160px;height:16px;border:solid #7F9DB9 1px;' /></div><div class='list' style='height:185px;overflow:auto;float:left;clear:both'></div>";
	
	$("#insertblock .inner").html(html);
	
	$("#at_keyword").keyup(function(){
		var word = $(this).val();
		getFriendsSelector(word, showList)
	});
	

	var showList = function(results){
		var html = "<dl>";
		for(k in results){
			var val = results[k];
			html += "<dd>@" + val["nickname"] + "</dd>";
		}
		html += "</dl>";
		$("#insertblock .inner .list").html(html);
		$("#insertblock .inner dl dd").click(function(){
			var name = $(this).html();
			insertText2Textarea(cobj,name + " ");
			countWord($("#weibo_content"), $("#word_count"));
		});
	}
	getFriendsSelector("", showList);
}

function getFriendsSelector(word, call){
	if(word != ""){
		var actionURL = "https://api.weibo.com/2/search/suggestions/at_users.json?q=" + word + "&count=" + 10;
	} else {
		var actionURL = "https://api.weibo.com/2/friendships/friends/bilateral.json?uid=" + uid + "&count=200";
	}
    var message = {
        method: "get",
		action:actionURL
    };
	var requestBody = OAuth.formEncode(message.parameters);
    var request = newXMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
			if (request.status == 200){
				var results = JSON.parse(request.responseText);
				var data = new Array();
				
				if(word == ""){
					for(k in results["users"]){
						var val = results["users"][k]; 
						data[k] = {"nickname":val["screen_name"]}
					}
				} else {
					data = results;
				}
				call(data);
			}
        }
    };

	request.open(message.method, message.action, true); 
	request.setRequestHeader("Authorization", "OAuth2 " + accessToken);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.send(requestBody);
}

function getEmotionSelector(){
	var html = "<ul>";
	for(k in facesList){
		html += "<li><img src='" + facesList[k] + "' title='" + k + "' /></li>";
	}
	html + "</ul>";
	return html;
}

function insertText2Textarea(obj, val) {   
	//IE support   
	if (document.selection){   
		obj.focus();   
		sel = document.selection.createRange();   
		sel.text = val;   
		sel.select();   
	}else if (obj.selectionStart || obj.selectionStart == '0'){
		//MOZILLA/NETSCAPE support   
		var startPos = obj.selectionStart;
		var endPos = obj.selectionEnd;   
		// save scrollTop before insert   
		var restoreTop = obj.scrollTop;   
		obj.value = obj.value.substring(0, startPos) + val + obj.value.substring(endPos,obj.value.length);
		console.log("%d %d",startPos,endPos);
		if (restoreTop > 0){   
			// restore previous scrollTop   
			obj.scrollTop = restoreTop;   
		}   
		obj.focus();   
		obj.selectionStart = startPos + val.length;   
		obj.selectionEnd = startPos + val.length;   
	} else {   
		obj.value += val;   
		obj.focus();   
	}   
} 

function listenAtSelector(obj){
	if (obj.selectionStart || obj.selectionStart == '0'){
		var startPos = obj.selectionStart;
		var str = obj.value.substring(0, startPos);
		n = str.lastIndexOf("@");
		if(n >= 0){			
			var word = obj.value.substr(n+1, startPos+2);
			if(word.indexOf(" ") < 0){
				getFriendsSelector(obj, word);
			} else {
				$("#friendsselector").remove();
			}
			console.log("%d %d %s",n,startPos,word);
		}
	}
}

function selectText(obj,start,end){
	if(document.selection){
		if(obj.tagName=='TEXTAREA'){
			var i=obj.value.indexOf("\r",0);
			while(i!=-1&&i<end){
				end--;
				if(i<start){
					start--;
				}
				i=obj.value.indexOf("\r",i+1);
			}
		}
		var range=obj.createTextRange();
		range.collapse(true);
		range.moveStart('character',start);
		if(end!=undefined){
			range.moveEnd('character',end-start);
		}
		range.select();
	}else{
		obj.selectionStart=start;
		var sel_end=end==undefined?start:end;
		obj.selectionEnd=Math.min(sel_end,obj.value.length);
		obj.focus();
	}
}

function countWord(ele1, ele2){
	var ts = $(ele2);
	var str = $(ele1).val();
	var n = Math.ceil(strlen(str) / 2); //调用方法
	pd = wordCountLimit - n;
	if(wordCountLimit - n > 0){
		ts.html("您还可以输入<b>" + (wordCountLimit-n) + "</b>字");
	}else{
		$("#word_count").html('已经超出<b style="color:#ff0000">'+(n-wordCountLimit)+'</b>个字');
	}
}

//记录输入的文字到localstorage
function saveWord2Storage(key, str){
	localStorage.setItem(key, str);
}

//发微薄
function postWeibo(text){
	$(".post_loading").show();
	var message = {method: 'POST', action: accessor.serviceProvider.postDataURL};
	var requestPost = newXMLHttpRequest();
	requestPost.onerror = function(e){
		showMsgTip("网络连接错误！", $("body"), 140,200, "#ff0000");
	}
	requestPost.onreadystatechange = function(){
		if (requestPost.readyState == 4){
			if (requestPost.status == 200){
				results = OAuth.decodeForm(requestPost.responseText);
				$(".post_loading").hide();
				saveWord2Storage("weibo_content", "");
				$("#weibo_content").val("");
				$("#weibobox").animate({top:100},100, "linear", function(){$("#insertblock").remove();$("#weibobox_container").hide();});
				$("#tip_success").fadeIn();
				setTimeout(function(){$("#tip_success").fadeOut();}, 2000);
				showDataLoading();
				$(".tablist span.on").removeClass("on");
				$(".tablist span[feature='0']").addClass("on");
				getDataFromApi("weibo", {"refresh":1, "feature":0});
			} else {
				results =  JSON.parse(requestPost.responseText);
				if(results["error_code"] == "20019"){
					showMsgTip("请不要重复发表内容！", $("#weibobox_container"), 120,40, "#ff0000");			
				}else{
					showMsgTip("微博发表失败，请重试！", $("#weibobox_container"), 120,40, "#ff0000");
				}
				$(".post_loading").hide();
				return;
			}
		}
	};

	requestPost.open(message.method, message.action, true);
	requestPost.setRequestHeader("Authorization", "OAuth2 " + accessToken);
    //requestPost.setRequestHeader("Content-Type", "multipart/form-data");
	requestPost.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	data = encodeURIComponent(text);
	requestPost.send('status=' + data);
};

//发表评论后的回调函数
function callbackAfterComment(results, ele){
	var tempList1 = results["created_at"].split(" ");
	var tempList2 = tempList1[3].split(":");
	var createTime = tempList1[1] + " " + tempList1[2] + " " + tempList2[0] + ":" + tempList2[1];
	var verifiedHtml = "";
	var reg = new RegExp("<.*>(.*)<\/a>"); 
	var source = results["source"].replace(reg,"$1");
	var commentText = searchFace(results["text"]);
	var delHtml = "";
	if(results["user"]["verified"]){
		verifiedHtml = "<b>V</b>";
	}
	if(results["user"]["id"] == uid){
		delHtml = "&nbsp;&nbsp;<a class='delete' cid='" + results["id"] + "'>删除</a><span></span>";
	}
	var dataHtml = "<li><span class='profile_image'><img src='" + results["user"]["profile_image_url"] + "' height=32 width=32 uname='" + results["user"]["name"] + "' /><span></span></span><span class='comment_uname'><screen_name>" + results["user"]["name"] + "</screen_name><span></span>" + verifiedHtml + "</span>：" +commentText + "</li><li class='comment_info'>" + createTime + " "+source+"<span class='reply'>回复</span></li>";

	if($(ele + " .nocomment").html() != null){
		$(ele + " .nocomment").html("<ul>" + dataHtml + "</ul>");
	} else {
		$(ele + " ul").prepend(dataHtml);
	}
	$(ele + " .input_comment").val("");
}

//发评论
function postComment(id, text, ele, repost, repostText){
	if(text == ""){
		showMsgTip("评论内容不能为空！",ele, 100,130, "#ff0000");
		return;
	}
	var message = {method: 'POST', action: "https://api.weibo.com/2/comments/create.json"};
	var requestPost = newXMLHttpRequest();
	requestPost.onerror = function(e){
		showMsgTip("网络连接错误！", $("body"), 140,200, "#ff0000");
	}
	requestPost.onreadystatechange = function(){
		if (requestPost.readyState == 4){
			if (requestPost.status == 200){
				results =  JSON.parse(requestPost.responseText);
				if(ele.indexOf("#comment") == 0){
					callbackAfterComment(results, ele);
				} else if(ele.indexOf("#reply_box") == 0){
					$(ele).fadeOut();
					$(ele).html("");
				}
				if(repost == 1){
					postRepost(id, repostText, 0, 0);
				}
				$("#tip_success").fadeIn();
				setTimeout(function(){$("#tip_success").fadeOut();}, 2000);
			} else {
				results =  JSON.parse(requestPost.responseText);
				if(results["error_code"] == "20019"){
					showMsgTip("请不要重复发表内容！", ele, 100,130, "#ff0000");			
				}else{
					showMsgTip("评论发表失败，请重试！", ele, 100,130, "#ff0000");
				}
				return;
			}
		}
	};

	requestPost.open(message.method, message.action, true);
	requestPost.setRequestHeader("Authorization", "OAuth2 " + accessToken);
	requestPost.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	data = encodeURIComponent(text);
	requestPost.send('comment=' + data + "&id=" + id);
};

//转发
function postRepost(id, text, comment, call){
	console.log(id);
	var commentStr = (comment == 1) ? "&is_comment=1" : "";
	var message = {method: 'POST', action: "https://api.weibo.com/2/statuses/repost.json"};
	var requestPost = newXMLHttpRequest();
	requestPost.onerror = function(e){
		showMsgTip("网络连接错误！", $("body"), 140,200, "#ff0000");
	}
	requestPost.onreadystatechange = function(){
		if (requestPost.readyState == 4){
			if (requestPost.status == 200){
				if(call == 0){
					return;
				}
				results = JSON.parse(requestPost.responseText);
				$("#comments_list_"+id).fadeOut();
				$("#tip_success").fadeIn();
				setTimeout(function(){$("#tip_success").fadeOut();}, 2000);
				$("#content").animate({scrollTop:0},200);
				showDataLoading();
				$(".tablist span.on").removeClass("on");
				$(".tablist span[feature='0']").addClass("on");
				getDataFromApi("weibo", {"refresh":1, "feature":0});
			} else {
				var ele = $("#comments_list_"+id);
				results =  JSON.parse(requestPost.responseText);
				if(results["error_code"] == "20019"){
					showMsgTip("请不要重复发表内容！", ele, 100,130, "#ff0000");			
				}else{
					showMsgTip("评论发表失败，请重试！", ele, 100,130, "#ff0000");
				}
				return;
			}
		}
	};

	requestPost.open(message.method, message.action, true);
	requestPost.setRequestHeader("Authorization", "OAuth2 " + accessToken);
	requestPost.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	data = encodeURIComponent(text);
	requestPost.send('status=' + data + "&id=" + id + commentStr);
};

function getMyFavFromLocal(){
	var myFavoritesStr = localStorage.getItem("myfavorites");
	if(!checkIfLocal(myFavoritesStr)){
		myFavorites = {}
	} else {
		myFavorites = JSON.parse(myFavoritesStr);
	}
	return myFavorites;
}

//收藏或取消收藏
function postFav(id, type){
	var myFavorites = getMyFavFromLocal();
	var actionURL = (type == "create") ? "https://api.weibo.com/2/favorites/create.json" : "https://api.weibo.com/2/favorites/destroy.json";
	var message = {method: 'POST', action: actionURL};
	var requestPost = newXMLHttpRequest();
	requestPost.onerror = function(e){
		showMsgTip("网络连接错误！", $("body"), 140,200, "#ff0000");
	}
	requestPost.onreadystatechange = function(){
		if (requestPost.readyState == 4){
			if (requestPost.status == 200){
				if(type == "destroy"){
					//loadingFavorites();
					if(dataType == "favorite"){
						$("#weibo_" + id).animate({height:0}, 200, "linear", function(){$("#weibo_" + id).next("li").remove();$("#weibo_" + id).remove();});
					} else {
						$("#weibo_" + id + " .addfav").html("收藏");
					}
					var newFavorites = deleteEleFromDict(id, myFavorites)
					localStorage.setItem("myfavorites", JSON.stringify(newFavorites));
				} else {
					myFavorites[id] = 1;
					$("#weibo_" + id + " .addfav").html("取消收藏");
					localStorage.setItem("myfavorites", JSON.stringify(myFavorites));
				}
			}
		}
	};

	requestPost.open(message.method, message.action, true);
	requestPost.setRequestHeader("Authorization", "OAuth2 " + accessToken);
	requestPost.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    requestPost.send("id="+id);
}

function initUserdataLoading(html){
	showCloseWeiboPostBox("close");
	$("#panelbar .tablist").remove();
	$("#panelbar").height(28);
	$("#panelbar").css("overflow", "hidden");
	$("#panelbar").append(html);
	$("#navbar span.on").removeClass("on");
	$("#userbar").css("top","-80px");
	$("#content").height(newContentHeight);
	showDataLoading();
	$("#content").animate({scrollTop:0},200);
}

//加载我的微博列表
function loadingMyWeibo(){
	var html = "<div class='tablist'><span class='on'>我的微博</span></div>";
	initUserdataLoading(html);
	dataType = "weibo";
	getDataFromApi("userweibo", {"screen_name":userInfo["name"],"readcache":1});
	var lastAction = {"method":"loadingMyWeibo"};
	saveAction(lastAction);
}

//加载我的收藏列表
function loadingFavorites(){
	var html = "<div class='tablist'><span class='on'>我的收藏</span></div>";
	initUserdataLoading(html);
	dataType = "favorite";
	getDataFromApi("favorite", {"readcache":1});
	var lastAction = {"method":"loadingFavorites", "type":dataType};
	saveAction(lastAction);
}

function loadingWeibo(ele, feature){
	var feature = feature ? feature : 0;
	$("#panelbar .tablist").remove();
	var html = "<div class='tablist'><span feature='0' class='on'>全部</span><span feature='1'>原创</span><span feature='2'>图片</span><span  feature='3'>视频</span><span feature='4'>音乐</span></div>";
	$("#panelbar").append(html);
	$(".tablist span.on").removeClass("on");
	$(".tablist span[feature='" + feature + "']").addClass("on");
	dataType = "weibo";
	preDataLoading(ele);
	if(newWeiboCount > 0){
		$("#content").animate({height:newContentHeight}, 300, "linear", getDataFromApi("weibo", {"refresh":1, "feature":feature}));
	} else {
		$("#content").animate({height:newContentHeight}, 300, "linear", getDataFromApi("weibo", {"readcache":1, "feature":feature}));
	}
	
	var lastAction = {"method":"loadingWeibo", "feature":feature};
	saveAction(lastAction);
	
	$(".tablist span").click(function(){
		dataType = "weibo";
		preDataLoading(ele);
		$(".tablist span.on").removeClass("on");
		$(this).addClass("on");
		var feature1 = parseInt($(this).attr("feature"));
		getDataFromApi("weibo", {"readcache":1, "feature":feature1});
		var lastAction = {"method":"loadingWeibo", "feature":feature1};
		saveAction(lastAction);
		localStorage.setItem("weibo_feature", feature1);
	});
}

function loadingFans(type, theUid){
	$("#panelbar .tablist").remove();
	var who = "我";
	var html = "<div class='tablist'><span id='btn_fans' class='on'>" + who + "的粉丝</span><span id='btn_friends'>" + who + "的关注</span></div>";
	$("#panelbar").append(html);
	dataType = type;
	$(".tablist span.on").removeClass("on");
	$("#btn_" + type).addClass("on");
	preDataLoading($("#new_fans"));
	$("#content").animate({height:newContentHeight}, 300, "linear", getDataFromApi(type,{"refresh":1, "uid":theUid}));
	$("#btn_fans").click(function(){
		dataType = "fans";
		preDataLoading($("#new_fans"));
		getDataFromApi("fans",{"refresh":1, "uid":theUid});
		$(".tablist span.on").removeClass("on");
		$(this).addClass("on");
		var lastAction = {"method":"loadingFans", "type":"fans", "theUid":theUid};
		saveAction(lastAction);
	});
	$("#btn_friends").click(function(){
		dataType = "friends";
		preDataLoading($("#new_fans"));
		getDataFromApi("friends",{"refresh":1, "uid":theUid});
		$(".tablist span.on").removeClass("on");
		$(this).addClass("on");
		var lastAction = {"method":"loadingFans", "type":"friends", "theUid":theUid};
		saveAction(lastAction);
	});
	var lastAction = {"method":"loadingFans", "type":dataType, "theUid":theUid};
	saveAction(lastAction);
}

function loadingComments(type){
	$("#panelbar .tablist").remove();
	var html = "<div class='tablist'><span class='on' id='btn_comment_tome'>收到的评论</span><span id='btn_comment_byme'>发出的评论</span></div>";
	$("#panelbar").append(html);
	dataType = type;
	$(".tablist span.on").removeClass("on");
	$("#btn_" + type).addClass("on");
	preDataLoading($("#new_comment"));
	$("#content").animate({height:newContentHeight}, 300, "linear", getDataFromApi("comment_tome",{"refresh":1}));
	$("#btn_comment_byme").click(function(){
		dataType = "comment_byme";
		preDataLoading($("#new_comment"));
		getDataFromApi("comment_byme",{"refresh":1});
		$(".tablist span.on").removeClass("on");
		$(this).addClass("on");
	});
	$("#btn_comment_tome").click(function(){
		dataType = "comment_tome";
		preDataLoading($("#new_comment"));
		getDataFromApi("comment_tome",{"refresh":1});
		$(".tablist span.on").removeClass("on");
		$(this).addClass("on");
	});
	var lastAction = {"method":"loadingComments", "type":type};
	//localStorage.setItem("lastaction", JSON.stringify(lastAction));
	saveAction(lastAction);
}

function loadingAtme(){
	$("#panelbar .tablist").remove();
	var html = "<div class='tablist'><span class='on'>@我的微博</span></div>";
	$("#panelbar").append(html);
	dataType = "atme";
	preDataLoading($("#new_atme"));
	$("#content").animate({height:newContentHeight}, 300, "linear", getDataFromApi("atme",{"refresh":1}));
	var lastAction = {"method":"loadingAtme"};
	//localStorage.setItem("lastaction", JSON.stringify(lastAction));
	saveAction(lastAction);
}

function listenNavClick(uid){
	$("#screen_name a").click(function(){
		var url = "http://weibo.com/" + uid + "/profile";
		createNewTab(url);
	});

	$("#new_msg").click(function(){
		var url = "http://weibo.com/messages?source=toptray";
		createNewTab(url);
	});

	$("#new_fans").click(function(){
		loadingFans("fans", uid);
	});

	$("#new_comment").click(function(){
		loadingComments("comment_tome");
	});

	$("#new_atme").click(function(){
		loadingAtme();
	});

	$("#new_weibo").click(function(){
		var feature = localStorage.getItem("weibo_feature");
		feature = checkIfLocal(feature) ? feature : 0;
		loadingWeibo($(this), feature);
	});

	$("#setting").click(function(){
		 chrome.extension.showOptionPage();
		 window.close();
	});
	
	var logOut = function(){
		var jsonData = {cmd:"logout",value:1};
		doPostMessage(jsonData);

		for(k in localStorage){
			if(k != "welcome_pop" && k != "show_wizard"){
				localStorage.setItem(k, "");
			}
		}
		endSession();
		if($("#weibobox_container").css("display") != "none"){
			showCloseWeiboPostBox("close");
		}
		return;
	}
	
	$("#logout").click(function(){
		var ele = $("#footer");
		initConfirmBox(ele, "确认要退出登录吗？", 0 , logOut, {"left":"195px", "top":"-85px"});
	});
	
	$("#writelong").click(function(){
		chrome.windows.create({url:"long.html",width:600,height:610,left:400,top:200,type:"popup"});
		window.close();
	});
	$("#postpic").click(function(){
		chrome.windows.create({url:"image.html",width:600,height:410,left:400,top:200,type:"popup"});
		window.close();
	});
	$("#share").click(function(){
		chrome.windows.getLastFocused(function(w){
			chrome.tabs.getSelected(w.id, function(tab){
				var title = encodeURIComponent(tab.title);
				var url = encodeURIComponent(tab.url);
				chrome.windows.create({url:"post.html?title="+title+"&url="+url,width:595,height:362,left:400,top:200,type:"popup"});
				window.close();
			});
		});
	});
}

//退出登录
function endSession(){
	var message = {method: 'GET', action: "https://api.weibo.com/2/account/end_session.json"};
	var requestBody = OAuth.formEncode(message.parameters);
	var request = newXMLHttpRequest();
	request.onerror = function(e){
		showMsgTip("网络连接错误！", $("body"), 140,200, "#ff0000");
	}
	request.onreadystatechange = function(){
		if (request.readyState == 4){
			if (request.status == 200){
				chrome.browserAction.setBadgeText({text:""}) 
				gotoAuthPage();
				$("#main").hide();
				jsonData = {cmd:"logout",value:1};
				doPostMessage(jsonData);
			}
		}
	};
	request.open(message.method, message.action, true); 
	request.setRequestHeader("Authorization", "OAuth2 " + accessToken);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.send(requestBody);
}

function createNewTab(url){
	chrome.windows.getLastFocused(function(w){
		chrome.tabs.getSelected(w.id, function(tab){
			chrome.tabs.create({windowId:tab.windowId, index:tab.index+1, url:url, selected: true});
			jsonData = {cmd:"read",value:1};
			doPostMessage(jsonData);
			//window.close();
		});
	});
}

function getEmotions(){
	var cacheData = WeiboCache.getCache("emotions_list");
	if(cacheData){
		return;
	}
	var message = {
		method: "get", action:accessor.serviceProvider.emoionsURL
		, parameters: [["scope", "http://www.google.com/m8/feeds/"]]
	};
	var requestBody = OAuth.formEncode(message.parameters);
	var request = newXMLHttpRequest();
	request.onreadystatechange = function receiveData() {
		if (request.readyState == 4) {
			if (request.status == 200){
				results = request.responseText;
				var cacheKey = "emotions_list";
				WeiboCache.setCache(cacheKey, results, 7200);
			}
		}
	};
	request.open(message.method, message.action, true); 
	request.setRequestHeader("Authorization", "OAuth2 " + accessToken);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.send(requestBody);
}

function initFacesList(){
	try{
		var str = localStorage.getItem("emotions_list");
		if(!checkIfLocal(str)){
			getEmotions();
		}
		var results = JSON.parse(str);
		if(results != null){
			var emotiosList = JSON.parse(results["val"]);
		}
	}catch(e){
		var emotiosList = {}
	}
	for(k in emotiosList){
		facesList[emotiosList[k]["value"]] = emotiosList[k]["icon"];
	}
}

function searchFace(str){	
	var reg = /\[[^\[\]]+\]/ig; 
	var matchList = str.match(reg);
	//initFacesList();
	if(matchList != null && matchList != undefined){
		for(k in matchList){
			try{
				if( facesList[matchList[k]]){
					var title = matchList[k].replace("[", "");
					var title = title.replace("]", "");
					str = str.replace(matchList[k],"<img class='face' width=22 height=22 src='" + facesList[matchList[k]] + "' alt='" + title + "' title='" + title + "' />");
				}
			}catch(e){
			}
		}
	}
	return str;
}

//微博内容列表的展示
function showWeiboList(data, showType, page){
	var html = "<div id='weibo_list_" + page +"'><ul>";
	var len = data.length;
	var reg = new RegExp("<.*>(.*)<\/a>"); 
	var myFavorites = getMyFavFromLocal();
	console.log(myFavorites);
	for(var i = 0; i < len; i ++){
		try{
			var val = data[i];
			if(val["deleted"] != undefined && val["deleted"] == "1"){
				continue;
			} else {
				var tempList1 = val["created_at"].split(" ");
				var tempList2 = tempList1[3].split(":");
				var createTime = tempList1[1] + " " + tempList1[2] + " " + tempList2[0] + ":" + tempList2[1];
				var source = val["source"].replace(reg,"$1");
				var weiboText = searchAtLink(val["text"]);
				weiboText = searchTinyLink(weiboText);
				weiboText = searchFace(weiboText);
				var imgHtml = "";
				var retweetedHtml = "";
				var verifiedHtml = "";
				if(val["thumbnail_pic"] != "" && val["thumbnail_pic"] != undefined){
					imgHtml = "<div class='weibopic'><img src='" + val["thumbnail_pic"] + "' class='weibo_pic' nPic='" +  val["bmiddle_pic"] + "' nWidth=0 /><a class='weibopic_bar' href='" + val["original_pic"] + "'>查看大图</a></div>";
				} else {
					if(val["retweeted_status"] != "" && val["retweeted_status"] != undefined){
						var imgHtml1 = "";
						if(val["retweeted_status"]["thumbnail_pic"] != "" && val["retweeted_status"]["thumbnail_pic"] != undefined){
							imgHtml1 = "<div class='weibopic'><img src='" + val["retweeted_status"]["thumbnail_pic"] + "' class='weibo_pic' nPic='" +  val["retweeted_status"]["bmiddle_pic"] + "' nWidth=0 /><a class='weibopic_bar' href='" + val["retweeted_status"]["original_pic"] + "'>查看大图</a></div>";
						}
						var verifiedHtml1 = "";
						if(val["retweeted_status"]["user"]["verified"] ){
							verifiedHtml1 = "<b>V</b>";
						}
						var weiboText1 = searchAtLink( val["retweeted_status"]["text"]);
						var weiboText1 = searchTinyLink(weiboText1);
						weiboText1 = searchFace(weiboText1);
						var createTime1 ="";
						var tempList3 = val["retweeted_status"]["created_at"].split(" ");
						var tempList4 = tempList3[3].split(":");
						var createTime1 = tempList3[1] + " " + tempList3[2] + " " + tempList4[0] + ":" + tempList4[1];
						retweetedHtml = "<div class='retweeted_topbar'></div>";
						retweetedHtml += "<div class='retweeted'><screen_name uid='" + val["retweeted_status"]["user"]["id"] + "'>@" + val["retweeted_status"]["user"]["name"] + "</screen_name><span></span>"+verifiedHtml1+"：" + weiboText1 + imgHtml1 + "<div class='rinfo' name='" + val["id"] + "_" + val["retweeted_status"]["id"] + "' ><span>" + createTime1 + "</span><a class='reposts_count' name='retweeted'>转(" + val["retweeted_status"]["reposts_count"] + ")</a>&nbsp;&nbsp;<a class='comments_count' name='retweeted'>评(" + val["retweeted_status"]["comments_count"] + ")</a></div><div  id='comments_list_r_" + val["id"] + "_" + val["retweeted_status"]["id"] + "' class='comments_list_weibo_r'></div></div>";
						retweetedHtml += "<div  id='weibo_text_" + val["id"] + "' style='display:none'>//@" +  val["user"]["screen_name"] + ":" +val["text"]+"</div>";
						//retweetedHtml += "<div  id='comments_list_" + val["retweeted_status"]["id"] + "' class='comments_list_weibo_r'></div>";
					}
				}
				if(val["user"]["verified"]){
					verifiedHtml = "<b>V</b>";
				}
				var description = "";
				if(val["user"]["description"]){
					description = val["user"]["description"];
				}
				var vreason = "";
				if(val["user"]["verified_reason"]){
					vreason = val["user"]["verified_reason"];
				}
				var delHtml = "";
				if(val["user"]["id"] == uid){
					delHtml = "<a class='delete'>删</a><span></span>&nbsp;&nbsp;";
				}
				var favHtml = "";
				if(val["favorited"] == false && myFavorites[val['id']] == undefined){
					favHtml = "收藏";
				}else{
					favHtml = "取消收藏";
				}
				html += "<li id='weibo_" + val['id'] + "'><span class='profile_image'><img src='" + val["user"]["profile_image_url"] + "' height=32 width=32 uname='" + val["user"]["name"] + "' /><span></span></span>"
				html += "<div class='text'><span class='creattime'>" + createTime + "</span><span class='screen_name'><screen_name uid='" + val["user"]["id"] + "'>" + val["user"]["screen_name"] + "</screen_name><span></span>" + verifiedHtml + "</span><br>" + weiboText + imgHtml + retweetedHtml;
				html += "<div class='info'>来自"+source+"<div class='comment_bar' name='" + val['id'] + "'>"+delHtml+"<a class='addfav'>" + favHtml + "</a><span></span>&nbsp;&nbsp;<a class='reposts_count'>转(" + val["reposts_count"] + "</a>)&nbsp;&nbsp;<a class='comments_count'>评(" + val["comments_count"] + "</a>)</div></div>"
				html += "<div id='comments_list_" + val["id"] + "' class='comments_list_weibo'></div></div></li><li class='line'></li>";
			}
		}catch(e){continue}
	}
	html += "</ul></div>";
	removeDataLoading();
	if(showType == "replace"){
		$("#content").html(html);
	} else {
		$("#content").append(html);
	}
	if(dataType == "atme"){
		resetUnread(2);
		$("#new_atme b").fadeOut();
		$("#new_atme b").html("");
	} 
		
	
	$("#weibo_list_" + page + " .comments_count").click(function(){
		var id = $(this).parent().attr("name");
		var tempName = $(this).attr("name");
		if(tempName == "retweeted"){
			var ele = $("#comments_list_r_" + id);
			var tempArr = id.split("_");
			id = tempArr[1];
		} else {
			var ele = $("#comments_list_" + id);
		}
		//var ele = (tempName == "retweeted") ? $("#comments_list_r_" + id) : $("#comments_list_" + id);
		if(ele.css("display") != "none" && ele.attr("name") == "comment"){
			ele.hide();
			ele.attr("name", "");
		} else {
			getCommentsOfWeibo(ele, id);
		}		
	});

	$("#weibo_list_" + page + " .reposts_count").click(function(){
		var id = $(this).parent().attr("name");
		var tempName = $(this).attr("name");
		var ele = (tempName == "retweeted") ? $("#comments_list_r_" + id) : $("#comments_list_" + id);
		if(ele.css("display") != "none" && ele.attr("name") == "repost"){
			ele.hide();
			ele.attr("name", "")
		} else {
			showRepostBox(ele, id);
		}	
	});

	var cancelFav = function(id){
		postFav(id, "destroy");
	}
	$("#weibo_list_" + page + " .addfav").click(function(){
		console.log(dataType);
		var id = $(this).parent().attr("name");
		if($(this).text() == "收藏"){
			postFav(id, "create");
		} else {
			var ele = $(this).next("span");
			initConfirmBox(ele, "确认要取消收藏此微博吗？", id , cancelFav, {"left":"-150px", "top":"-95px"});
			
		}
	});

	$("#weibo_list_" + page + " .delete").click(function(){
		var id = $(this).parent().attr("name");
		var ele = $(this).next("span");
		initConfirmBox(ele, "确认要删除这条微博吗？", id , delWeibo);
	});
	
	$(".weibopic_bar").click(function(){
		var url = $(this).attr("href");
		chrome.windows.getLastFocused(function(w){
			chrome.tabs.getSelected(w.id, function(tab){
				chrome.tabs.create({windowId:tab.windowId, index:tab.index+1, url:url, selected: true});
			});
		});
		return false;
	});
	loadWeiboPic("#weibo_list_" + page);
	showProfileCard("#weibo_list_" + page + " .profile_image img", "img");
	showProfileCard("#weibo_list_" + page + " screen_name", "text");
	visitUserWeibo("#weibo_list_" + page);
	visitTinyLink("#weibo_list_" + page);
}

//删除微博
function delWeibo(id){
	for(k in localStorage){
		if(k.indexOf("weibo_list") > 0){
			localStorage.setItem(k, "");
		}
	}
	deleteData("weibo", id)
}

//删除评论
function delComment(cid){
	deleteData("comment", cid)
}

//访问短链接
function visitTinyLink(ele){
	$(ele + " tinylink").click(function(){
		var tinyUrl = $(this).html();
		createNewTab(tinyUrl);
	});
}

//访问别人的微博
function gotoUserWeibo(uid, name, type1){
	showCloseWeiboPostBox("close");
	$("#panelbar").css("overflow", "hidden");
	var type1 = type1 ? type1 : "userweibo";
	$("#navbar span.on").removeClass("on");
	$("#userbar").remove();
	var userbarHtml = "<div id='userbar'><img src='images/loading.gif' class='loading1' /></div>";
	$("#panelbar").append(userbarHtml);
	clearTimeout(showCardTime);	
	$(".profile_card").remove();
	$("#content").animate({scrollTop:0},200);
	$("#content li").fadeOut("slow");
	showDataLoading();
	if(uid != ""){
		
	} else {
		if(userInfo["name"] != name) {
			$("#panelbar").height(65);
			$("#content").height(newContentHeight - 37);
			$("#userbar").animate({top:0}, "300", "linear", function(){
				getUserInfo(name, "userbar", type1)
			});	
			saveRecentViews(name);
			saveMostViews(name);
		} else {
			$("#panelbar").height(28);
			$("#userbar").css("top","-80px");
			$("#content").height(newContentHeight);
			getDataFromApi("userweibo", {"screen_name":name,"refresh":1,"noresult":0});
		}
		
	}
	var lastAction = {"method":"gotoUserWeibo","uid":uid,"name":name, "type":type1};
	//localStorage.setItem("lastaction", JSON.stringify(lastAction));
	saveAction(lastAction);
}

function saveRecentViews(name){
	var nameListStr = localStorage.getItem("recentview_list");
	var newNameList = new Array();
	newNameList[0] = name;
	if(checkIfLocal(nameListStr)){
		var nameList = JSON.parse(nameListStr);
		var i = 0;
		for(k in nameList){
			if(nameList[k] != name){
				i ++;
				newNameList[i] = nameList[k];
				if(i == 100){
					break;
				}
			}
		}
	}
	nameListStr = JSON.stringify(newNameList);
	localStorage.setItem("recentview_list", nameListStr);
}

function delFromRecentViews(name){
	var nameListStr = localStorage.getItem("recentview_list");
	var newNameList = new Array();
	if(checkIfLocal(nameListStr)){
		var nameList = JSON.parse(nameListStr);
		var i = 0;
		for(k in nameList){
			if(nameList[k] != name){
				newNameList[i] = nameList[k];
				i ++;
			}
		}
	}
	nameListStr = JSON.stringify(newNameList);
	localStorage.setItem("recentview_list", nameListStr);
}

function saveMostViews(name, count){
	var nameListStr = localStorage.getItem("mostview_list");
	var nameList = {};
	
	if(checkIfLocal(nameListStr)){
		nameList = JSON.parse(nameListStr);
		if(count == 0){
			nameList[name] = 0;
		} else {
			if(nameList[name]){
				nameList[name] = nameList[name] + 1;
			} else {
				nameList[name] = 1;
			}
		}
	} else {
		nameList[name] = 1;
	}
	nameListStr = JSON.stringify(nameList);
	//return;
	localStorage.setItem("mostview_list", nameListStr);
}

function visitUserWeibo(ele){
	$(ele + " screen_name").click(function(){
		var name = $(this).html().replace("@", "");	
		gotoUserWeibo("", name);
	});
}

function sort(sortType, dict){
	var dictNew = {};
	var sortArr = new Array();
	var i = 0;
	for(k in dict){
		sortArr[i] = k;
		i ++;
	}
	var len = sortArr.length;
	var t;
	for(var n = 0;n < len; n++){
		for(var m = 0; m < len; m++){
			if((m+1 <= len) && (parseInt(dict[sortArr[m]]) < parseInt(dict[sortArr[m + 1]]))){
				t = sortArr[m];
				sortArr[m] = sortArr[m+1];
				sortArr[m+1] = t;
			}
		}
	}

	for(var k = 0; k < len; k ++){
		dictNew[sortArr[k]] = dict[sortArr[k]];
	}
	return dictNew;
}

//微博访问记录
function initWeiboHistory(){
	var namelistHideTime = "";
	var namelistShowTime = "";
	var html = "<div id='namelist'></div>";
	$("body").append(html);
	$(".history_view").mouseenter(function(){
		var right = $(this).css("right");
		if($("#namelist").css("display")!="none"){
			$("#namelist").animate({right:right});
		}else{
			$("#namelist").css("right",right);
		}
		var dataName = $(this).attr("data");
		namelistShowTime = setTimeout(function(){showNameList(dataName);},600);
	});
	
	$(".history_view").mouseleave(function(){
		clearTimeout(namelistShowTime);
		namelistHideTime = setTimeout(function(){
			
			//$("#namelist").fadeOut();
			//$("#namelist").remove();
			}, 1000
		);
	});
	$("#namelist").mouseenter(function(){
		clearTimeout(namelistHideTime);
	});
	$("#namelist").mouseleave(function(){
		$("#namelist").fadeOut();
		//$("#namelist").remove();
	});
	var showNameList = function(itemName){
		var nameListStr = localStorage.getItem(itemName);
		if(checkIfLocal(nameListStr)){
			if(itemName == "mostview_list"){
				var nameList = sort("", JSON.parse(nameListStr));
			} else {
				var nameList = JSON.parse(nameListStr);
			}
		} else {
			$("#namelist").html("<span style='padding:8px;color:#fff'>没有访问记录</span>");
			$("#namelist").fadeIn();
			return;
		}
		var n = 0;
		var m = 0;
		html1 = "<div class='list'><ul>";
		for(k in nameList){
			n ++;
			if(n > 15){
				break;
			}
			if(itemName == "mostview_list"){
				if(parseInt(nameList[k]) > 0 ){
					m = m + 1
					html1 += "<li>@<user>" + k + "</user> <b>(" + nameList[k] + ")</b><del></del></li>";
				}
			} else {
				html1 += "<li>@<user>" +  nameList[k] + "</user> <b>&nbsp;</b><del></del></li>";
			}
		}
		if(m == 0){
			$("#namelist").html("<span style='padding:8px;color:#fff'>没有访问记录</span>");
			$("#namelist").fadeIn();
			return;
		}
		html1 += "</ul></div>";
		html1 += "<div style='margin:5px 5px 0px 5px;text-align:right;padding:0px 4px 0px 4px;color:#eee;border-top:dotted #eee 1px;' class='clear'>[清除记录]</div>";
		$("#namelist").html(html1);
		$("#namelist").fadeIn();
		$("#namelist .list ul li").click(function(){
			var name = $(this).children("user").text();
			gotoUserWeibo("", name);
			showNameList(itemName);
			//$("#namelist").fadeOut();
		});
		$("#namelist .list ul li").mouseover(function(){
			$(this).children("del").show();
		});
		$("#namelist .list ul li").mouseout(function(){
			$(this).children("del").hide();
		});
		$("#namelist .list ul li del").click(function(){
			var name =  $(this).parent().children("user").text();
			if(itemName == "mostview_list"){
				saveMostViews(name, 0);
			} else {
				delFromRecentViews(name);
			}
			showNameList(itemName);
			return false;
		});
		$("#namelist .clear").click(function(){
			localStorage.setItem(itemName, "");
			showNameList(itemName);
			namelistHideTime = setTimeout(function(){
				$("#namelist").fadeOut();
			}, 1000
		);
		});
	}
}

//微博用户信息卡片
var showCardTime = "";
var hideCardTime = "";
var cardOutHtml = "<div class='profile_card'><div class='inner'><img src='images/loading.gif' style='margin:70px 0px 0px 140px' /></div><span class='$1'></span></div>";

function showProfileCard(eleName, eleType){
	$(eleName).mouseenter(function(){
		$(".profile_card").remove();
		clearTimeout(hideCardTime);
		clearTimeout(showCardTime);
		var ele = $(this);
		if(eleType == "img"){
			showCardTime = setTimeout(function(){showCardOfImg(ele)}, 1000);
		} else if(eleType == "img1"){
			showCardTime = setTimeout(function(){showCardOfImg(ele, "comment")}, 1000);
		} else {
			showCardTime = setTimeout(function(){showCardOfText(ele)}, 1000);
		}					
	});

	$(eleName).mouseleave(function(){
		clearTimeout(showCardTime);
		hideCardTime = setTimeout(function(){$(".profile_card").remove()}, 500);
	});
	
}

function showCardOfImg(ele,type){
	if(type == "comment"){
		var html = cardOutHtml.replace("$1", "arrow_x");
		var top = 20;
		var left = -40;
	}else {
		var html = cardOutHtml.replace("$1", "arrow_y");
		var top = -25;
		var left = 10;
	}
	$(ele).next("span").css("position", "relative");
	$(ele).next("span").append(html);
	var name = ele.attr("uname");
	
	
	var cardEle = $(".profile_card");
	if(type == "comment"){
		cardEle.children(".arrow_x").css("left","160px");
		cardEle.children(".arrow_x").animate({left:16});
	} else {
		cardEle.children(".arrow_y").animate({top:13});
	}
	cardEle.css("top", top + "px");
	cardEle.css("left", left + "px");
	cardEle.fadeIn();
	getUserInfo(name, "card");
	$(".profile_card").mouseover(function(){
		clearTimeout(hideCardTime);
		clearTimeout(showCardTime);
	});
	$(".profile_card").mouseleave(function(){
		clearTimeout(hideCardTime);
		clearTimeout(showCardTime);
		$(".profile_card").remove();
	});
}

function showCardOfText(ele){
	var html = cardOutHtml.replace("$1", "arrow_x");
	var name = ele.html().replace("@", "");
	$(ele).next("span").css("position", "relative");
	$(ele).next("span").append(html);
	var top = 22;
	var eleWidth = ele.width();
	eleWidth = (eleWidth > 200) ? 20 : eleWidth;
	
	var eleLeft = ele.offset().left;
	if(eleLeft < 180){
		var left = -(eleLeft - 40);
		var arrowLeft = eleLeft + eleWidth / 2 - 40;
	} else {
		var left = -(300 - (400 - eleLeft) + 20);
		var arrowLeft = 300 - (400 - eleLeft) + eleWidth / 2 + 20;
	}
		
	
	var cardEle = $(".profile_card");
	cardEle.children(".arrow_x").animate({left:arrowLeft});
	cardEle.css("left", left - eleWidth + "px");
	cardEle.css("top", top + "px");
	cardEle.fadeIn();
	getUserInfo(name, "card");

	$(".profile_card").mouseover(function(){
		clearTimeout(hideCardTime);
		clearTimeout(showCardTime);
	});
	$(".profile_card").mouseleave(function(){
		clearTimeout(hideCardTime);
		clearTimeout(showCardTime);
		$(".profile_card").remove();
	});	
}

function setFollow(following, follow_me, uid, ele){
	var uid = parseInt(uid);
	$(".follow1").click(function(){
		$(this).html("<img src='images/loading.gif' style='margin-top:-1px' />");
		followUser("create", uid, following, follow_me, ele);
	});

	$(".destroy").click(function(){
		var ele = $(this).next("span");
		initConfirmBox(ele, "确认要取消关注吗？", uid , destroy, {"left":"-195px", "top":"-95px"});
		
	});
	var destroy = function(uid){
		$(".destroy").html("<img src='images/loading.gif' style='margin-top:-1px' />");
		followUser("destroy", uid, following, follow_me, ele);
	}
}

function showCardInfo(results){
	if(!results){
		$(".profile_card .inner").html("<div class='noresult'>查无此人!</div>");
		return;
	}
	var verifiedHtml = "";
	if(results["verified"]){
		verifiedHtml = "<b>V</b>";
	}
	var imgSrc = results["profile_image_url"];		
	var nameHtml = results["name"] + verifiedHtml;
	var gender = formatGender(results["gender"]);
	var countFollowers = formatCount(parseInt(results["followers_count"]));

	var descHtml = "";
	if(results["verified_reason"] != ""){
		descHtml = results["verified_reason"];
	} else {
		if(results["description"] != ""){
			descHtml = "简介：" + results["description"].substr(0,40);
		} else {
			descHtml = "简介：暂无介绍";
		}
	}
	var uid = results["id"];
	var following = results["following"];
	var follow_me = results["follow_me"];
	//在线状态
	var onlineHtml = (results["online_status"] == 1) ? "<span class='online'></span>在线" : "<span class='notonline'></span>不在线";
	//alert(onlineHtml);
	var infoHtml = "<span class='location'>" + gender + " " + results["location"] + "</span><span class='info' name='" + results["name"] + "'>关注<user_friends>" + results["friends_count"] + "</user_friends> | 粉丝<user_fans>" + countFollowers + "</user_fans> | 微博<user_weibo>" + results["statuses_count"] + "</user_weibo></span>";
	var innerHtml = "<span class='card_profile_img'><img src='" + imgSrc + "' /></span><span class='screen_name'>" + nameHtml + "</span>" + infoHtml + "<span class='desc'>" + descHtml + "</span><div class='opbar'><div id='online_status'>" + onlineHtml + "</div><span id='friendship_"+uid+"'></span></div>";
	$(".profile_card .inner").html(innerHtml);
	showFriendship(following, follow_me, uid);
	$(".profile_card .inner user_weibo").click(function(){
		var name = $(this).parent().attr("name");
		gotoUserWeibo("", name, "userweibo");
	});
	$(".profile_card .inner user_fans").click(function(){
		var name = $(this).parent().attr("name");
		gotoUserWeibo("", name, "fans");
	});
	$(".profile_card .inner user_friends").click(function(){
		var name = $(this).parent().attr("name");
		gotoUserWeibo("", name, "friends");
	});
}

function showFriendship(following,follow_me,uid, ele){
	if(following == 1){
		var html = "<span class='follow'>已关注 | <a class='destroy'>取消</a><span></span></span>";
		if(follow_me == 1){
			var html = "<span class='follow'>互相关注 | <a class='destroy'>取消</a><span></span></span>";
		}
	} else {
		var followme = "";
		if(follow_me == 1){
			var followme = "√ ";
		}
		var html = "<span class='follow1' uid='"+ uid +"'><strong>"+followme+"+</strong>加关注</span>";
	}
	if(ele){
		$(ele).html(html);
	} else {
		$("#friendship_"+uid).html(html);
	}
	setFollow(following, follow_me, uid, ele);
}

//转发框
function showRepostBox(ele, id){
	var repostHtml = "转发微博：<br /><textarea class='input_repost' rows=1></textarea><div class='bar_postcomment'><span class='check'><input type='checkbox' name='repost' id='comment_check_" + id + "' />同时发一条评论</span><span class='btn_repost_post'>转 发</span></div>";
	ele.html(repostHtml);
	ele.attr("name", "repost");
	ele.fadeIn();
	
	var inputEle = $("#comments_list_"+id+" .input_repost");
	inputEle.keyup(function(){
		//$("#keyword").val($(this).attr("scrollHeight"));
		$(this).height($(this).attr("scrollHeight") - 4);
	});
	if($("#weibo_text_" + id).html() != null){
		var repostText = $("#weibo_text_" + id).html();
		inputEle.val(repostText);
	}
	inputEle.height(inputEle.attr("scrollHeight") - 4);
	id1 = ele.attr("id");
	$("#" + id1 + " .btn_repost_post").click(function(){
		var data = $("#" + id1 + " .input_repost").val();
		var repostData = (data == "") ? "转发微博" : data;
		var comment = 0;
		if($("#comment_check_"+ id).attr("checked")){
			comment = 1;
		} 
		id = id.indexOf("_") > 0 ? id.substr(id.indexOf("_") + 1) : id;
		console.log(id);
		repostData = repostData.substr(0,140);
		postRepost(id, repostData, comment);
	});
}

function showCommentsOfWeibo(ele, results, id){
	var commentHtml = "<textarea class='input_comment' rows=1></textarea><div class='bar_postcomment'><span class='check'><input type='checkbox' name='repost' id='repost_check_" + id + "' />同时转发到我的微博</span><span class='btn_comment_post'>评 论</span></div>";
	var reg = new RegExp("<.*>(.*)<\/a>"); 
	var dataHtml = "<ul>";
	var len = results.length;
	for(var i = 0; i < len; i ++){
		var val = results[i];
		var verifiedHtml = "";
		var tempList1 = val["created_at"].split(" ");
		var tempList2 = tempList1[3].split(":");
		var createTime = tempList1[1] + " " + tempList1[2] + " " + tempList2[0] + ":" + tempList2[1];
		if(val["user"]["verified"]){
			verifiedHtml = "<b>V</b>";
		}
		var description = "";
		if(val["user"]["description"]){
			description = val["user"]["description"];
		}
		var vreason = "";
		if(val["user"]["verified_reason"]){
			vreason = val["user"]["verified_reason"];
		}
		
		var commentText= searchAtLink(val["text"]);
		commentText = searchTinyLink(commentText);
		commentText = searchFace(commentText);
		var source = val["source"].replace(reg,"$1");
		dataHtml += "<li><span class='profile_image'><img src='" + val["user"]["profile_image_url"] + "' height=32 width=32 uname='" + val["user"]["name"] + "' /><span></span></span><span class='comment_uname'><screen_name>" + val["user"]["name"] + "</screen_name><span></span>" + verifiedHtml + "</span>：" +commentText + "</li><li class='comment_info'>" + createTime + " "+source+"<span class='reply'>回复</span></li>";
	}
	dataHtml += "</ul>";
	
	if(len == 0){
		ele.html(commentHtml + "<div class='nocomment' style='padding-left:10px'>此微博还没有评论！</div>");
	} else {
		ele.html(commentHtml + dataHtml);
	}
	ele.attr("name", "comment");
	var eleId = ele.attr("id");
	showProfileCard("#" + eleId + " .profile_image img", "img1");
	showProfileCard("#" + eleId + " screen_name", "text");
	$("#" + eleId + " .input_comment").keyup(function(){
		//$("#keyword").val($(this).attr("scrollHeight"));
		$(this).height($(this).attr("scrollHeight") - 4);
	});
	$("#" + eleId + " .btn_comment_post").click(function(){
		var data = $("#" + eleId + " .input_comment").val();
		if($("#weibo_text_" + id).html() != null){
			var repostText = $("#weibo_text_" + id).html();
			var repostData = data + repostText;
			repostData = repostData.substr(0,140);
		}  else {
			var repostData = data;
		}
		
		if($("#repost_check_"+ id).attr("checked")){
			postComment(id, data, "#" + eleId, 1, repostData);	
		} else {
			postComment(id, data, "#" + eleId, 0, "");
		}
		
	});

	$("#" + eleId + " .reply").click(function(){
		var name = $(this).parent().prev("li").children("span").children("screen_name").html();
		
		$("#" + eleId + " .input_comment").focus();
		$("#" + eleId + " .input_comment").val("回复@" + name + ":");
		
		
	});

	visitUserWeibo("#" + eleId);
}

function showCommentsList(data, type, showType, page){
	var html = "<div id='comments_list_" + page + "'><ul>";
	var len = data.length;
	if (len == 0){
		$("#content").html("<div style='padding:20px;color:#999'>目前还没有评论！</div>");
		return;
	}
	var reg = new RegExp("<.*>(.*)<\/a>"); 
	for(var i = 0; i < len; i ++){
		var val = data[i];
		var weiboText = searchAtLink(val["status"]["text"]);
		weiboText = searchTinyLink(weiboText);
		weiboText = searchFace(weiboText);
		var weiboId = val["status"]["id"];
		var tempList1 = val["created_at"].split(" ");
		var tempList2 = tempList1[3].split(":");
		var createTime = tempList1[1] + " " + tempList1[2] + " " + tempList2[0] + ":" + tempList2[1];
		var source = val["source"].replace(reg,"$1");
		var replyHtml = "";
		var verifiedHtml = "";
		var delHtml = "";
		var replyBoxHtml = "";
		console.log(val);
		if(val["reply_comment"] != "" && val["reply_comment"] != undefined){
			try{
				replyHtml = "<div style='color:#307D74'><font color='#aaa'>回复 " + val["reply_comment"]["user"]["name"] + " 的评论</font>：”" + val["reply_comment"]["text"] + "“</div>";
			} catch(e){
				replyHtml = "<div style='color:#307D74'>" + val["reply_comment"]["text"] + "“</div>";
			}
			var commentType = "comment";
		}else if(val["status"] != "" && val["status"] != undefined){
			replyHtml = "<div style='color:#307D74'><font color='#aaa'>评论 " + val["status"]["user"]["name"] +" 的微博</font>：”" + weiboText + "“</div>";
			var commentType = "weibo";
		}
		
		if(val["user"]["verified"]){
			verifiedHtml = "<b>V</b>";
		}
		
		if(val["user"]["id"] == uid){
			delHtml = "<span class='delete1'><a cid='" + val["id"] + "'>删除</a><span></span></span>";
		} else {
			replyBoxHtml = "<span class='reply' replyid='" +val["id"] + "' weiboid='" + weiboId + "' >回复</span>";
		}
		html += "<li id='comment_" + val["id"] + "'><span class='profile_image'><img src='" + val["user"]["profile_image_url"] + "' height=32 width=32 uname='" + val["user"]["name"] + "' /></span><div class='text'><span class='screen_name'><screen_name>" + val["user"]["screen_name"] + "</screen_name><span></span>" + verifiedHtml + "</span>：" + val["text"] + replyHtml + "<div class='info'>" + createTime + " &nbsp;&nbsp;来自"+source+delHtml + replyBoxHtml + "</div></div><div id='reply_box_" + val["id"] + "' class='reply_box' replyname='" + val["user"]["screen_name"] + "' text='" + val["text"] + "'></div></li><li class='line'></li>";
	}
	html += "</ul>";
	if(showType == "replace"){
		$("#content").html(html);
	} else {
		$("#content").append(html);
	}
	resetUnread(1);
	$("#new_comment b").fadeOut();
	$("#new_comment b").html("");

	$("#comments_list_" + page + " .delete1 a").click(function(){
		var cid = $(this).attr("cid");
		var ele = $(this).next("span");
		initConfirmBox(ele, "确认要删除这条评论吗？", cid , delComment, {"left":"-200px", "top":"-95px"});
	});

	$("#comments_list_" + page + " .reply").click(function(){
		var id = $(this).attr("replyid");
		var weiboId = $(this).attr("weiboid");
		var ele = "#reply_box_" + id;
		if($(ele).html() == ""){
			showReplyBox(ele, weiboId);
		} else {
			$(ele).fadeOut();
			$(ele).html("");
		}
	});

	var showReplyBox = function(ele, id){
		var replyBoxHtml = "<textarea class='input_comment' rows=1></textarea><div class='bar_postcomment'><span class='check'><input type='checkbox' name='repost' id='repost_check_" + id + "' />同时转发到我的微博</span><span class='btn_comment_post'>评 论</span></div>";
		$(ele).html(replyBoxHtml);
		$(ele).fadeIn();
		var name = $(ele).attr("replyname");
		
		$(ele).children(".input_comment").html("回复@" + name + ":");
		$(ele).children(".input_comment").keyup(function(){
			$(this).height($(this).attr("scrollHeight") - 4);
		});
		$(ele).children("div").children(".btn_comment_post").click(function(){
			var data = $(ele).children(".input_comment").val();
			var repostData
			if($("#repost_check_"+ id).attr("checked")){
				var repostText = "@" + name + ":" + $(ele).attr("text");
				var repostData = data + "//" + repostText;
				repostData = repostData.substr(0,140);
				postComment(id, data, ele, 1, repostData);	
			} else {
				postComment(id, data, ele, 0, "");
			}
			
		});
	}
	removeDataLoading();
	showProfileCard("#comments_list_" + page + " .profile_image img", "img");
	showProfileCard("#comments_list_" + page + " screen_name", "text");
	visitUserWeibo("#comments_list_" + page);
}

function showFollowsList(data, showType, page){
	var html = "<div id='users_list_" + page +"'><ul>";
	var len = data.length;
	for(var i = 0; i < len; i ++){
		var val = data[i];
		var verifiedHtml = "";
		var statusHtml = "";
		var locationHtml = "";
		if(val["verified"]){
			verifiedHtml = "<b>V</b>";
		}
		if(val["status"] != "" && val["status"] != undefined){
			statusHtml = val["status"]["text"];
		}
		if(val["location"] != "" && val["location"] != undefined){
			locationHtml = val["location"];
		}
		var gender = formatGender(val["gender"]);
		//在线状态
		var onlineHtml = (val["online_status"] == 1) ? "<span class='online'></span>" : "<span class='notonline'></span>";
		html += "<li><span class='profile_image'><img src='" + val["profile_image_url"] + "' height=32 width=32 /></span><div class='text' style='padding-bottom:8px' name='" + val["name"] + "' uid='" + val["id"] + "'><screen_name>" + val["name"] + "</screen_name>" + verifiedHtml + "<br />" + gender + "&nbsp;&nbsp;" + locationHtml + "&nbsp;&nbsp;&nbsp;粉丝<user_fans>" + val["followers_count"] + "</user_fans>人&nbsp;&nbsp;关注<user_friends>" + val["friends_count"] + "</user_friends>人&nbsp;&nbsp;微博<user_weibo>" + val["statuses_count"] + "</user_weibo><br /><font color='#9ABBC8'>" + val["description"] + "<font></div></li>";
	}
	html += "</ul>";
	if(showType == "replace"){
		$("#content").html(html);
	} else {
		$("#content").append(html);
	}
	removeDataLoading();
	resetUnread(4);
	$("#new_fans b").fadeOut();
	$("#new_fans b").html("");
	visitUserWeibo("#users_list_" + page);
	$("#users_list_" + page + " user_weibo").click(function(){
		var name = $(this).parent().attr("name");
		gotoUserWeibo("", name, "userweibo");
	});
	$("#users_list_" + page + " user_fans").click(function(){
		var name = $(this).parent().attr("name");
		gotoUserWeibo("", name, "fans");
	});
	$("#users_list_" + page + " user_friends").click(function(){
		var name = $(this).parent().attr("name");
		gotoUserWeibo("", name, "friends");
	});
}

var page = 1;
var configData = {"noresult":0, "refresh":1}
var max_id = 0;
var timeout = 0;

//从接口读取数据
function getDataFromApi(type, data){
	var noresult = 0;
	var timeout = 1;
	dataLoading = 1;
	dataType = type;
	var data1 = data;
	refresh = 0;
	if(data["refresh"] == 1){
		page = 1;
		max_id = 0;
		var showType = "replace";
	} else if(data["readcache"] == 1){
		page = 1;
		var showType = "replace";
		configData = data;
		if(type == "weibo"){
			var feature = data["feature"] ? data["feature"] : 0;
			var cacheData = WeiboCache.getCache("home_weibo_list_" + feature);
			if(cacheData){
				var weiboData = cacheData["val"];
				max_id = weiboData["next_cursor"];
				showWeiboList(weiboData["statuses"], showType, 1);
				dataLoading = 0;
				page ++;
				data["noresult"] = 0;
				return;
			} else {
				page = 1;
				max_id = 0;
				var showType = "replace";
			}
		}else if(type == "userweibo" && (uid == data["uid"] || userInfo["screen_name"] == data["screen_name"])){
			configData["screen_name"] = data["screen_name"];
			var cacheData = WeiboCache.getCache("myweibo_list");
			if(cacheData){
				var weiboData = cacheData["val"];
				max_id = weiboData["next_cursor"];
				showWeiboList(weiboData["statuses"], showType, 1);
				dataLoading = 0;
				page ++;
				data["noresult"] = 0;
				return;
			}

		}
	}
	
	if(type == "atme"){
		var actionURL = "https://api.weibo.com/2/statuses/mentions.json?count=" + readCount + "&page=" + page;
		var key = "statuses";
	}else if(type == "favorite") {
		var actionURL = "https://api.weibo.com/2/favorites.json?count=" + readCount + "&page=" + page;
		var key = "favorites";
	}else if(type == "comment_tome"){
		var actionURL = "https://api.weibo.com/2/comments/to_me.json" + "?count=" + readCount + "&page=" + page;
		var key = "comments";
	}else if(type == "comment_byme"){
		var actionURL = "https://api.weibo.com/2/comments/by_me.json" + "?count=" + readCount + "&page=" + page;
		var key = "comments";
	} else if(type == "fans"){
		var next_cursor = (page - 1) * 50;
		var actionURL = "https://api.weibo.com/2/friendships/followers.json?uid=" + data["uid"];
		actionURL += "&count=50&cursor=" + next_cursor;
		var key = "users";
	} else if(type == "friends"){
		var next_cursor = (page - 1) * 50;
		var actionURL = "https://api.weibo.com/2/friendships/friends.json?uid=" + data["uid"];
		actionURL += "&count=50&cursor=" + next_cursor;
		var key = "users";
	}else if(type == "userweibo"){
		var actionURL = "https://api.weibo.com/2/statuses/user_timeline.json";
		actionURL += (data["screen_name"]) ? "?screen_name=" + data["screen_name"] : "?uid=" + data["uid"];
		actionURL += "&count=" + readCount + "&page=" + page;
		var key = "statuses";
	} else {
		var feature = data["feature"] ? data["feature"] : 0;
		var actionURL = accessor.serviceProvider.homeTimelineURL + "?count=" + readCount + "&max_id=" + max_id + "&feature=" + feature;
		var key = "statuses";
	}

    var message = {
        method: "get", action: actionURL
		 , parameters: [["scope", "http://www.google.com/m8/feeds/"]]
    };
    var requestBody = OAuth.formEncode(message.parameters);
	var request = newXMLHttpRequest();
    request.onreadystatechange = function receiveData() {
        if (request.readyState == 4) {
			clearTimeout(rt);
			if (request.status == 200){
				timeout = 0;
				//clearTimeout(rt);
				var results = request.responseText;
				try{
					var weiboData = JSON.parse(results);
				} catch(e){
					var weiboData = eval("(" + results + ")");
				}
				if(weiboData[key].length == 0 && page != 1){
					var noresult = 1;
					removeDataLoading();
					data["noresult"] = 1;
				} else {
					if(type == "comment_tome" || type == "comment_byme"){
						showCommentsList(weiboData["comments"], type, showType, page);
					} else if(type == "fans" || type == "friends"){
						showFollowsList(weiboData["users"] ,showType, page);
					} else if(type == "favorite") {
						favoritesList = [];
						for(n in weiboData["favorites"]){
							var val = weiboData["favorites"][n];
							val["status"]["favorited"] = true;
							favoritesList[n] = val["status"];
						}
						showWeiboList(favoritesList, showType, page);
					} else {
						//写缓存，5分钟自动更新一次
						if(page == 1){
							if(type == "weibo"){
								var cacheKey = "home_weibo_list_" + feature;;
								WeiboCache.setCache(cacheKey, results, 300);
								$("#new_weibo b").fadeOut();
								$("#new_weibo b").html("");
								newWeiboCount = 0;
							}else if(type == "userweibo" && (uid == data["uid"] || userInfo["screen_name"] == data["screen_name"])){
								var cacheKey = "myweibo_list";
								WeiboCache.setCache(cacheKey, results, 300);
							}
							
						}
						max_id = weiboData["next_cursor"];
						showWeiboList(weiboData["statuses"], showType, page);
					}
					data["noresult"] = 0;
				}

				dataLoading = 0;
				configData = data;
				page ++;

				//向后台发送通知，更新未读信息条数
				jsonData = {cmd:"openpop",value:1};
				doPostMessage(jsonData);
			}else {
				var results = JSON.parse(request.responseText);
				if(results["error"] == "invalid_access_token"){
					//clearTimeout(rt);
					gotoAuthPage();
					return;
				} else if(results["error_code"] == "21321"){
					showErrorBlock("对不起，接口调用超过限制!");
					return;
				} else if(results["error_code"] == "21327"){
					//showErrorBlock("对不起，授权码已过期，请重新登录！");
					gotoAuthPage();
					return;
				}else {
					showErrorBlock("数据加载失败，请重试!");
				}

			}
       		}
	};
	var rt = setTimeout(function(){showErrorBlock("数据加载超时，请重试！");}, 15000);
	request.open(message.method, message.action, true); 
	request.setRequestHeader("Authorization", "OAuth2 " + accessToken);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	//设置两秒超时
	request.send(requestBody);
	
}

function getCommentsOfWeibo(ele, id){
	//var commentHtml = "<div class='comments_list' id='comments_list_" + id + "'>数据加载中...</div>";
	//ele.append(commentHtml);
	ele.fadeIn();
	ele.html("数据加载中...");
	var message = {
        method: "get", action: "https://api.weibo.com/2/comments/show.json?id=" + id
		 , parameters: [["scope", "http://www.google.com/m8/feeds/"]]
    };
    var requestBody = OAuth.formEncode(message.parameters);
	var request = newXMLHttpRequest();
    request.onreadystatechange = function receiveData() {
        if (request.readyState == 4) {
           if (request.status == 200){
				var results = JSON.parse(request.responseText);
				
				showCommentsOfWeibo(ele, results["comments"], id);				
			}
        }
    };

    request.open(message.method, message.action, true); 
    request.setRequestHeader("Authorization", "OAuth2 " + accessToken);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.send(requestBody);
}


//授权页
function gotoAuthPage(){
	var oauthCallback = encodeURIComponent(accessor.serviceProvider.authCallbackURL);
	var userAuthorizationURL = accessor.serviceProvider.userAuthorizationURL;
	var appkey = accessor.consumerKey;
	var authURL = userAuthorizationURL + "?client_id=" + appkey + '&response_type=token&redirect_uri=' + oauthCallback + "&dsiplay=popup";
	$("#loadingblock").remove();
	window.resizeTo(authWindowWidth,authWindowHeight);
	$("#myiframe").attr("src", authURL);
	$("#myiframe").fadeIn();
}

//获取授权码
function getAccessToken(){
	console.log("getAccessToken");
	$("#myiframe").load(function(){
		var myFrame = document.getElementById("myiframe");
		try{
			var fDoc = myFrame.contentWindow.document;
				fDoc.getElementsByTagName("*");
				var listElm = fDoc.getElementsByTagName("*");
				var elmLen = listElm.length;
				for(var i = elmLen - 1; i >= 0; i--){
					if(listElm[i].className == "app_pic"){
						listElm[i].src = "images/logo.png";
						break;
					}else if(listElm[i].className == "oauth_submit"){
						var newHtml = listElm[i].innerHTML.replace("同时登录微博", "");
						listElm[i].innerHTML = newHtml;
					}
				}
		}catch(e)
		{
			//return;
		}
		
		var accessTokenNew = $(this).contents().find("#access_token").html();

		if(accessTokenNew != undefined){
			localStorage.setItem("oauth2_accessToken", accessTokenNew);
			accessToken = accessTokenNew;
			window.resizeTo(400,222);
			$("#myiframe").hide();
			getUidByAccessToken();
			$("#panelbar").fadeIn();
			loadingWeibo($("#new_weibo"));
			initFacesList();
		}
	});
}

function saveAction(action){
	var actionStr =  JSON.stringify(action);	
	var actionListStr = localStorage.getItem("history_action");
	if(checkIfLocal(actionListStr)){
		var actionList = JSON.parse(actionListStr);
		if(actionList[0] == actionStr){
			return;
		}
		actionList.unshift(actionStr);
	} else {
		var actionList = new Array();
		actionList[0] = actionStr;
	}
	if(actionList.length > 20){
		actionList.pop();
	}
	var actionListStrNew = JSON.stringify(actionList);
	localStorage.setItem("history_action", actionListStrNew);
}

function doHistoryAction(n){
	var actionListStr = localStorage.getItem("history_action");
	if(checkIfLocal(actionListStr)){
		var actionList = JSON.parse(actionListStr);
		var lastActionResults = JSON.parse(actionList[n]);
		var method = lastActionResults["method"];
		switch(method){
			case "gotoUserWeibo":
				var theUid = lastActionResults["uid"];
				var name = lastActionResults["name"];
				var type = lastActionResults["type"];
				gotoUserWeibo(theUid, name, type);
			break;
			case "loadingFans":
				var theUid = lastActionResults["theUid"];
				var type = lastActionResults["type"];
				loadingFans(type, theUid);
			
			break;
			case "loadingFavorites":
				loadingFavorites();
			break;
			case "loadingMyWeibo":
				loadingMyWeibo();
			break;
			case "loadingComments":
				var type = lastActionResults["type"];
				loadingComments(type);
			break;
			case "loadingAtme":
				loadingAtme();
			break;
			default:
				var feature = lastActionResults["feature"];
				loadingWeibo($("#new_weibo"), feature);
			break;
		}
	} else {
		loadingWeibo($("#new_weibo"));
	}
}

//根据操作系统决定使用哪种字体
function initFontFamily(){
	var customUa = 'unknow';
	var ua = navigator.userAgent.toLowerCase();
	var isWinXP = ua.indexOf("windows nt 5.1") > -1 || ua.indexOf("windows xp") >-1;
	//isWinXP = true;
	if(isWinXP){
		$("#fontstyle").attr("href", "css/st.css");
	}
}

function init(){
	initFontFamily();
	getAccessToken();
	var results = localStorage.getItem("oauth2_userinfo");
	if(checkIfLocal(results)){
		userInfo = JSON.parse(results);
		uid = parseInt(userInfo["id"]);
		showUserInfo(userInfo);
		window.resizeTo(400,newWindowHeight);
		$("#main").fadeIn();
		$("#panelbar").fadeIn();
		doHistoryAction(0);
	} else {
		showNoAcessBlock();
		getUidByAccessToken();
	}
	
	initWeiboHistory();
	listenDataRefresh();
	initWeiboTextpost();
	
}

function listenScroll(){
	$("#content").scroll(function(){
		var contentHeight =  parseInt($("#content").height());
		var scrollTop = parseInt($(this).scrollTop());
		var scrollHeight = parseInt($(this).attr("scrollHeight"));
		if((scrollTop + contentHeight + 10 > scrollHeight) && !$(".loadingbar").html() && (configData["noresult"] == 0)){
			var html = "<div class='loadingbar'><img src='images/loading.gif' />正在加载...</div>";
			$("#content").append(html);
			configData["refresh"] = 0;
			configData["readcache"] = 0;
			getDataFromApi(dataType, configData);
		}
	});
}

function initConfirmBox(ele, msg, id, callback, pos){
	$("#confirmbox_container").remove();
	ele.css("position","relative");
	var boxHtml = "<div id=\"confirmbox_container\"><div id=\"confirmbox\"><div class=\"inner\"><span class=\"msg\">" + msg + "</span><span class=\"confirm\"></span><span class=\"cancel\"></span></div></div></div>";
	ele.append(boxHtml);
	if(pos){
		var left = parseInt(pos["left"].replace("px", ""));
		var top = parseInt(pos["top"].replace("px", ""));
	} else {
		var left = -140;
		var top = -95;
	}
	var eleTop = ele.offset().top;
	var endTop = 95;
	if(eleTop - 130 < 125 ){
		top = top + 95 + 20;
		$("#confirmbox").css("top", "-95px");
		endTop = -95;
	}
	$("#confirmbox_container").css("top", top + "px");
	$("#confirmbox_container").css("left", left + "px");
	$("#confirmbox").animate({top:0}, 300, "linear", function(){});
	$("#confirmbox_container .cancel").click(function(){
		$("#confirmbox").animate({top:endTop}, 200, "linear", function(){$("#confirmbox_container").css("left","-400px");});
	});
	$("#confirmbox_container .confirm").click(function(){
		$("#confirmbox").animate({top:endTop}, 200, "linear", function(){callback(id)});
	});
}

function deleteData(type, id){
	var actionUrl = "";
	var data = "";
	switch(type){
		case "weibo":
			actionUrl = "https://api.weibo.com/2/statuses/destroy.json";
			data = "id="+id;
		break;
		case "comment":
			actionUrl = "https://api.weibo.com/2/comments/destroy.json";
			data = "cid="+id;
		break;
		default:
			actionUrl = "https://api.weibo.com/2/statuses/destroy.json";
			data = "id="+id;
		break;
	}
	var message = {
		method: "post",action:actionUrl
		, parameters: [["scope", "http://www.google.com/m8/feeds/"]]
	};
	var requestBody = OAuth.formEncode(message.parameters);
	var request = newXMLHttpRequest();
    request.onreadystatechange = function receiveData() {
        if (request.readyState == 4) {
			if (request.status == 200){
				if(type == "weibo"){
					$("#weibo_" + id).animate({height:0}, 200, "linear", function(){$("#weibo_" + id).next("li").remove();$("#weibo_" + id).remove();});
				} else if(type == "comment") {
					$("#comment_" + id).animate({height:0}, 200, "linear", function(){$("#comment_" + id).next("li").remove();$("#comment_" + id).remove();});
				}
			}else {
				return;
			}
        }
    };

    request.open(message.method, message.action, true); 
    request.setRequestHeader("Authorization", "OAuth2 " + accessToken);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.send(data);
}

function listenBackground(){
	port.onMessage.addListener(function messageHandler(response) {
		switch (response.cmd) {
			case "unread":
				var results = response.data;
				newWeiboCount = results["status"];
				showUnreadInfo(results);
			break;

		}
	});
}

function showErrorBlock(msg){	
	$("#errorbox_container").remove();
	var boxHtml = "<div id=\"errorbox_container\"><div id=\"errorbox\"><div class=\"inner\"><span class=\"msg\">" + msg + "</span><span class=\"redo\"></span><span class=\"cancel\"></span></div></div></div>";
	$("body").append(boxHtml);
	$("#errorbox").animate({top:0},300,"linear",function(){removeDataLoading();});
	
	$("#errorbox .cancel").click(function(){
		$("#errorbox").animate({top:125}, 200, "linear", function(){doHistoryAction(1);$("#errorbox_container").remove();});
	});
	$("#errorbox .redo").click(function(){
		$("#errorbox").animate({top:125}, 200, "linear", function(){doHistoryAction(0)});
	});
}

function showMsgTip(msg, pele, x, y, color){
	$("#tip_msg").remove();
	var html = "<div id='tip_msg' style='position:absolute;top:" + y + "px;left:" + x+ "px;;border-radius:5px;box-shadow:1px 2px 2px #bbb;opacity:0.9;z-index:9999;background:#fff;width:160px;height:28px;padding-top:12px;display:none;color:" + color + ";text-align:center;border:solid #ddd 1px;'>" + msg + "</div>";
	$(pele).append(html);
	$("#tip_msg").fadeIn();
	setTimeout(function(){$("#tip_msg").fadeOut();}, 3000);

}

function showNoAcessBlock(){
	var html = "<div id='loadingblock' style='position:absolute;left:0px;top:0px;width:400px;height:222px;background: url(images/loading.png);z-index:9999;color:#fff'><img src='images/loading.gif' style='position:absolute;left:10px;top:200px;'/><span style='position:absolute;left:29px;top:198px;'></span></div>";
	$("body").append(html);
}

//引导界面（用户教育）
function initWizard(){
	startWizard = 1;
	$("#weibo_content").val("我正在使用Chrome上的微博插件，挂微博方便，还能够及时提醒，发布、评论、转发微博更方便！试试吧！http://weibo.wantgame.net");
	var html ="<div id='wizard_overflow' style='width:400px;height:" + newWindowHeight + "px;background:#000;opacity:0.7;position:absolute;left:0px;top:0px;z-index:99999'></div><div id='tip_pop' style='position:absolute;right:5px;top:130px;width:120px;height:55px;padding:20px 7px 0px 10px;text-align:left;background:url(images/publish_tip.png);border-radius:8px;z-index:1000000;color:#3B90D1;font-size:14px;'></div>";
	$("body").append(html);
	$("#wizard_overflow").click(function(){
		$("#tip_pop").fadeOut();
		$(this).fadeOut();
		startWizard = 0;
		$("#weibo_content").val("");

	});

	$("#tip_pop").click(function(){
		$("#wizard_overflow").fadeOut();
		$(this).fadeOut();
		startWizard = 0;
		$("#weibo_content").val("");
	});
	localStorage.setItem("show_wizard", 1);
}

$(document).ready(function(){
	init();
	doCreatePort();
	search();
	listenScroll();
	listenBackground();
});
</script>

 <script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-33560959-2']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

</head>
<body>
<div class="loading"><img src='images/loading.gif' /></div>
<iframe width=670 height=480 border=0 frameborder=0 id='myiframe' style="display:none"></iframe>
<div id="main" style="display:none">
<div id="header">
	<div id="profile_image"></div>
	<div id="screen_name"></div>
	<div id="mystats"></div>
	<div id="search">
		<input type="text" value="搜索微博、找人" name="keyword" id="keyword" />
		<div id="btn_search"></div>
	</div>
</div>
<div id="navbar">
	<span id="new_weibo">首页<b></b></span>
	<span id="new_msg">私信<b></b></span>
	<span id="new_comment">评论<b></b></span>
	<span id="new_fans">粉丝<b></b></span>
	<span id="new_atme">我<b></b></span>
	<span id='writeweibo'>写微博</span>
</div>
<div id="stage">
		<div id="panelbar">
			<span id="mostview" class="history_view" data="mostview_list">最常浏览</span><span class="refresh"></span>
		</div>

		<div id="content"></div>
		<div id="footer">
			<span id="version">1.0.1</span>
			<a id="feedback" href="http://weibo.wantgame.net" target="_blank">[反馈]</a>
			<div id="setting">[设置]</div>
			<div id="logout">[退出]</div>
		</div>
	</div>
</div>

<div id="weibobox_container">
	<div id="weibobox">
		<span style="position:absolute;top:3px;left:6px;color:#bbb">有什么新鲜事想告诉大家？<input type="hidden" value="" name="ctype" id="contenttype" /><input type="hidden" value="" name="wurl" id="wurl" /> </span>
		<textarea id="weibo_content"></textarea>
		<span id="btn_weibo_post">发 布</span>
		<div id="postpic">发图片</div>
		<div id="writelong">长微博</div>
		<img src="images/loading.gif" class='post_loading' />
		<span class="close"></span>
		<span id="word_count" style="position:absolute;top:0px;right:45px;">还可以输入法<b>140</b>字</span>
		<div class="insertbar">
			<span class="emotions"><b></b>表情</span>
			<span class="topic"><b></b>话题</span>
			<span class="friends"><b></b>朋友</span>
		</div>
	</div>
</div>
<div id="tip_success" style="position:absolute;top:300px;left:137px;;border-radius:5px;box-shadow:1px 2px 2px #bbb;opacity:0.9;z-index:9999;background:url(images/publish_success.png) no-repeat;width:146px;height:36px;display:none;"></div>
</div>
</body>
</html>